Showing posts with label Python Programs. Show all posts
Showing posts with label Python Programs. Show all posts

Friday, January 15, 2021

Python Directory Methods

 

Method

Description

clear()

Removes all the elements from the dictionary

copy()

Returns a copy of the dictionary

fromkeys()

Returns a dictionary with the specified keys and value

get()

Returns the value of the specified key

items()

Returns a list containing a tuple for each key value pair

keys()

Returns a list containing the dictionary's keys

pop()

Removes the element with the specified key

popitem()

Removes the last inserted key-value pair

setdefault()

Returns the value of the specified key. If the key does not exist: insert the key, with the specified value

update()

Updates the dictionary with the specified key-value pairs

values()

Returns a list of all the values in the dictionary


Thursday, January 14, 2021

Python Directories

 Python Dictionaries are storage location and values are stored in key:value pair. It cannot have duplicate key and if we insert duplicate key, it will overwrite the existing one.

mdict = {

  "brand": "Ford",

  "model": "Mustang",

  "year": 1964

}

A dictionary is a collection which is unordered, changeable and does not allow duplicates.

mdict = {

  "brand": "Ford",

  "model": "Mustang",

  "year": 1964

}

print(mdict) will display all key and values.

Dictionary items are presented in key:value pairs, and can be referred to by using the key name.

Example

Print the "brand" value of the dictionary:

mdict = {

  "brand": "Ford",

  "model": "Mustang",

  "year": 1964

}

print(mdict["brand"])


Duplicates Not Allowed

Dictionaries cannot have two items with the same key:

Duplicate values will overwrite existing values:

mdict = {

  "brand": "Ford",

  "model": "Mustang",

  "year": 1964,

  "year": 2020

}

"year": 2020 will overwrite "year": 1964


Accessing Directory Items

We can access the items of a dictionary by referring to its key name, inside square brackets:


Example

Get the value of the "India" key:


mdict = {

  "India":"Delhi",

  "Bangladesh": "Dhaka",

  "Sri Lanka": "Colombo"

}

x = mdict["India"]

There is also a method called get() that will give you the same result:


Example

Get the value of the "India" key:


x = mdict.get("India")

Get Keys

The keys() method will return a list of all the keys in the dictionary.

x = dict.keys()

The list of the keys is a view of the dictionary, meaning that any changes done to the dictionary will be reflected in the keys list.


Add a new item to the original dictionary.

car = {

"India":"Delhi",

"Bangladesh": "Dhaka",

"Sri Lanka": "Colombo"

}

x = car.keys()


print(x) #before the change

car["China"] = "Beijing" # new key value pair added in the directory


Change Values in Directory

There are two techniques to change value in directory.

We can change the value of a specific item by referring to its key name:

Change the "Key1" to Value:

mdict = {

  "Key1":"Value1",

 "Key2":"Value2",

  "Key3":"Value3"

}

mdict["year"] = Value


Using update() method, we can change value and this method takes the new value along with key as argument.

Update the "Key3" of the car by using the update() method:

mdict = {

  "Key1":"Value1",

 "Key2":"Value2",

  "Key3":"Value3"

}

mdict.update({"Key3": Value})


Add Dictionary Items


This is same as updating directory. Using a new index key, we can assign value to add elements in directory. If the 'key' is existing, the value at that key will be updated.

Example

mdict = {

  "Key1":"Value1",

  "Key2":"Value2",

  "Key3":"Value3"

}

mdict["Key"] = "Value"


The update() method will update the dictionary with the items from a given argument. If the item does not exist, the item will be added.


The argument must be a dictionary, or an iterable object with key:value pairs.


Example

Add a color item to the dictionary by using the update() method:


mdict = {

  "Key1":"Value1",

  "Key2":"Value2",

  "Key3":"Value3"

}

mdict.update({"Key": "Value"})


Remove Dictionary Items


We can remove an item from directory using the pop () method. This method takes the 'key' as argument and remove the item.

Example

dict = {

  "Key1":"Value1",

  "Key2":"Value2",

  "Key3":"Value3"

}

mdict.pop("Key1")

del statement can remove an item with specified key like

del mdict["Key1"] # It will remove the item associated with the key "Key1"

To delete entire directory use: del mdict

To empty a directory, clear () method is called on the directory like : mdict.clear()


The popitem() method will remove the last inserted element. In versions before 3.7, it will remove any random item

mdict = {

  "Key1":"Value1",

  "Key2":"Value2",

  "Key3":"Value3"

}

mdict.popitem()


Copy Directories

copy () method can copy a directory into a new one and return it.

Example

mdict = {

  "Key1":"Value1",

  "Key2":"Value2",

  "Key3":"Value3"

}

mndict=dict.copy()


dict() function can copy an existing directory into another

mndict=dict(mdict)


Nested Directories

Nested directory means directory under directory

myfamily = {
  "child1" : {
    "name" : "Sata",
    "year" : 1997
  },
  "child2" : {
    "name" : "Suddha",
    "year" : 2004
  }
}

Similarly we can create directories separately and put them inside another directory

child1 = {
    "name" : "Sata",
    "year" : 1997
  }
  child2 = {
    "name" : "Suddha",
    "year" : 2004
  }

myfamily = {
  "child1" : child1,
  "child2" : child2
}

Tuesday, January 12, 2021

Python Set

 

Python’s built-in set type has the following characteristics:

Sets are unordered.

Set elements are unique. Duplicate elements are not allowed.

A set itself may be modified, but the elements contained in the set must be of an immutable type.

A set can be created in two ways. First, you can define a set with the built-in set() function:


myset = {"Assam", "Banaras", "Chennai"}


Check if "Banaras" is present in a set:

myset = {"Assam", "Banaras", "Cherry"}

print("Banaras" in myset)

Output would be true


Using add () method, we can add an element to the set.

myset = {"Apple","Banaras","Chennai"}

myset.add("orange")


To add items from another set into the current set, use the update() method.

Add elements from secondset and myset into newset:

myset = {"Apple","Banaras","Chennai"}

secondset = {"Patna", "Mangalore", "Pune"}

myset.update(secondset)


Removing elements from set

There are two methods to remove an element from set.

remove () and discard(). Both the methods takes the element to be removed as argument. If the element is not present, remove method will flag an error while discard won't.

The clear() method empties the set:

myset = {"Assam", "Banaras", "Chennai"}

myset.clear()


The del keyword will delete the set completely

myset = {"Assam", "Banaras", "Chennai"}

del myset

pop() method removes an element, the last element from a set. Since set is unordered, we can't say which element will be removed.which element is last one 

myset = {"Assam", "Banaras", "Chennai"}

x = myset.pop()



Python Tuples

 Tuples are used to store multiple items in a single variable. It is like list in Python with few differences. A tuple is a collection which is ordered and unchangeable.

Tuples are written using first brackets.

mytuple = ("apple", "banana", "cherry")


Accessing Tuple Elements

Like list, indexes are automatically generated in tuple and index starts from 0. All accessing techniques are same as list. Adding elements, updating elements in tuple are same as list. 

We can multiply the elements in tuple using the following statements.


We can use the * operator:

mytuple = ("Assam", "Banaras", "Chennai")

ptuple = fruits * 2


ptuple will be like ("Assam", "Banaras", "Chennai","Assam", "Banaras", "Chennai")

Tuple Methods

Python has two built-in methods that you can use on tuples.


count() Returns the number of times a specified value occurs in a tuple
index() Searches the tuple for a specified value and returns the position of where it was found

Sunday, January 10, 2021

How To Join Lists In Python

 

In Python there are several techniques to join lists and one of the easiest ways are by using the + operator.

mlist1 = ["a", "b", "c"]

mlist2 = [1, 2, 3]

mlist3 = mlist1 + mlist2

Now mlist3 would be ['a', 'b', 'c', 1, 2, 3]

This '+' operator creates a new list and store the values of the lists. We can join several lists using + operator.


The other technique to join two lists are by appending all the items from one list into another list, one by one. No extra list will be created here. This is carried out using append () method.

Append mlist2 into mlist1:

mlist1 = ["a", "b" , "c"]

mlist2 = [1, 2, 3]

mlist1.append(mlist2)

Now mlist1 would be ['a', 'b', 'c', 1, 2, 3]


extend() method can do the same job as append () method. 

mlist1 = ["a", "b" , "c"]

mlist2 = [1, 2, 3]

mlist1.extend(mlist2)

Now mlist1 would be ['a', 'b', 'c', 1, 2, 3]


Saturday, January 9, 2021

How To Copy List In Python

 To copy an existing list to another in Python, we can use copy () function and the function is invoked on the existing list object. This function returns a new object in which the elements of the existing list is copied.

Copy a List

mylist = ["assam", "banaras", "chennai"]

clist = mylist.copy()


Another way to make a copy is to use the built-in method list().

Example

mylist = ["assam", "banaras", "chennai"]

clist = list(mylist)


Friday, January 8, 2021

How To Sort List Elements In Python

 List objects in Python have a sort() method that will sort the list alphanumerically, ascending, by default:

Example

Sort the list alphabetically:

mylist = ["Assam", "Asansol", "Banaras", "Delhi", "Odisha"]

mylist.sort()

After sorting the list would be like ["Asansol","Assam", "Banaras", "Delhi", "Odisha"]


Sort the list numerically:

mylist = [100, 50, 65, 82, 23]

mylist.sort()

After sorting the list would be like [23,50,65,82,100]


Sort Descending

To sort descending, use the keyword argument reverse = True in sort () function

Sort the list descending:

mylist = ["Assam", "Asansol", "Banaras", "Delhi", "Odisha"]

mylist.sort(reverse = True)

After sorting the list would be like ["Odisha","Delhi","Banaras", "Assam","Asansol" ]


Sort the list of numeric values in descending order

mylist = [100, 50, 65, 82, 23]

mylist.sort(reverse = True)

After sorting the list would be like [100,82,65,50,23]

Thursday, January 7, 2021

How To Remove Specified List Item In Python


In Python, we can remove elements from list using the value stored in the list or index number

The remove() method removes the specified item.

Example

Remove "Banaras":

mylist = ["Assam","Banaras","Chennai"]

mylist.remove("Banaras")

Now the list will be ["Assam","Chennai"]


Remove Specified Index

The pop() method removes values from list of the specified index.

Example

Remove the second item:

mylist = ["Assam","Banaras","Chennai"]

mylist.pop(1)

Now the list will be ["Assam","Chennai"]


If you do not specify the index, the pop() method removes the last item.

Example

Remove the last item:

mylist = ["Assam","Banaras","Chennai"]

mylist.pop()

The list will be ["Assam","Banaras"]


The del keyword also removes the specified index:

Example

Remove the first item:

mylist = ["Assam","Banaras","Chennai"]

del mylist[0]

Now the list will be ["Banaras","Chennai"]


The del keyword can also delete the list completely.

Example

Delete the entire list:

mylist = ["Assam","Banaras","Chennai"]

del mylist

Clear the List


The clear() method empties the list.

The list still remains, but without any elements.

Example

Clear the list content:

mylist = ["Assam","Banaras","Chennai"]

mylist.clear()


Wednesday, January 6, 2021

How To Change List Items In Python


Like many other programming languages, change value in List is possible in Python.

Change Item Value

To change the value of a specific item, refer to the index number:

 Example

Change the second item:

 mylist = ["Assam","Banaras","Chennai"]

mylist[1] = "Bangalore"

Present list will be ["Assam","Bangalore","Chennai"]


 Change a Range of Item Values

To change the value of items within a specific range, we have to specify the start and end index with new values. Changes will be done on consecutive indexes starting from start index to end index -1. 

Example

Change the values "Banaras" and "Chennai" with the values "blackcurrant" and "watermelon":

mylist = ["Assam","Banaras","Chennai", "Delhi","Kolkata","Mumbai"]

mylist[1:3] = ["Bihar", "Kerala"]

 The list will be ["Assam","Bihar","Kerala", "Delhi","Kolkata","Mumbai"]

 

Dynamic insertion is possible in Python. If we want to insert more items than you replace items, the new items will be inserted on consecutive locations and the the remaining items at right side will move accordingly. 

Example

Change the second value by replacing it with two new values: 

mylist = ["Assam","Banaras","Chennai"]

mylist[1:2] = ["Bihar", "Kerala"] (specified location was 1 to 1)

The list will be ["Assam","Bihar","Kerala", "Chennai"] ("Bihar" will be at index 1, "Kerala" at index 2 , "Chennai" at index 3) 

The length of the list will automatically change. 

Like dynamic insertion, dynamic deletion is possible in Python. If we want to insert less items than you replace items, the new items will be inserted on specified indexes.

 

Example

Change the second and third value by replacing it with one value: 

mylist = ["Assam","Banaras","Chennai"]

mylist[1:3] = ["Bihar"]

The list will looks like: ["Assam","Bihar"]

 

Insert Items

To insert a new list item, without replacing any of the existing values, we can use the insert() method. 

The insert() method inserts an item at the specified index:

 

Example

Insert "Bihar" as the third item:

mylist = ["Assam","Banaras","Chennai"]

mylist.insert(2, "Bihar") ( "Bihar" will be inserted at index 2 and "Chennai" will automatically shited to index 3)

The list will be ["Assam","Banaras","Bihar","Chennai"]

Append Items

To add an item to the end of the list, use the append() method:

Example
Using the append() method to append an item:

mylist = ["Assam","Banaras","Chennai"]
mylist.append("Mumbai")

Output will be: The list will be ["Assam","Banaras","Bihar","Mumbai"] 

Tuesday, January 5, 2021

How To Access List Items In Python

 

List items are indexed in Python and we can use index number to access them. Index starts from 0 and ends at length of the list -1

 Example

Print the second item of the list:

 mylist = ["Assam", "Banaras", "Chennai"]

print(mylist[1])

 Output: Banaras

 

Negative Indexing in Python is allowed and negative indexing means start from the end

 -1 refers to the last item, -2 refers to the second last item and so on

 Example

Print the last item of the list:

 mylist = ["Assam", "Banaras", "Chennai"]

print(mylist[-1])

 Output: Chennai

 

Range of indexes can be specified to access number of elements at a time. When specifying a range, the return value will be a new list with the specified items.

 Example

Return the third, fourth, and fifth item:

 mylist = ["Assam", "Banaras", "Chennai", "Delhi", "Goa", "Indore"]

print(mylist[startindex:endindex])

The search will start at index 'startindex' and end at 'endindex-1'. If the statement is print(mylist[2:5]), it will fetch values at index 2,3 and 4 and the output would be ['Chennai', 'Delhi', 'Goa']

 

If the 'startindex' is kept vacant, it will become 0

 mylist = ["Assam", "Banaras", "Chennai", "Delhi", "Goa", "Indore"]

print(mylist[:4])

It will fetch values from index 0 to index 3

 

If the 'endindex' is kept vacant, it will fetch values from specified 1st index to last index of the list.

Example

This example returns the items from "cherry" to the end:

 mylist = ["Assam", "Banaras", "Chennai", "Delhi", "Goa", "Indore"]

print(mylist[2:])

 It will display ['Chennai', 'Delhi', 'Goa', 'Indore']


Monday, January 4, 2021

Python Collections – Arrays

  

Collection means storage location of number of values in same named space location.

 

There are four collection data types in the Python programming language:

           List is a collection which is ordered and changeable. Duplicate elements can be stored in list. 

           Tuple is a collection which is ordered and unchangeable. It also allows duplicate elements. 

           Set is a collection which is unordered and unindexed. Duplicate elements not allowed here. 

           Dictionary is a collection which is unordered and changeable. Duplicate elements not allowed here. 

 

Python Lists

 Lists are used to store multiple items in a single variable. Lists are created using square brackets:

 Example

Create a List:

  mylist = ["Assam", "Benaras", "Chennai"]

print( mylist)

 Output will be: = [‘Assam’, ‘Benaras’, ‘Chennai’]

 

List with duplicate values

Example

Lists allow duplicate values:

  mylist = ["Assam", "Benaras", "Chennai", “Assam”]

print( mylist)

Output will be: = [‘Assam’, ‘Benaras’, ‘Chennai’, ‘Assam’]

 

 List Length

To determine how many items a list has, use the len() function:

 Example

Print the number of items in the list: 

 mylist = ["apple", "banana", "cherry"]

print(len( mylist))

 Output would be: 3

 

List Items - Data Types

 List items can be of any data type:

 Example

String, int and boolean data types:

 list1 = ["Assam", "Benaras", "Chennai"]

list2 = [1, 5, 7, 9, 3]

list3 = [True, False, False]

 

A list can contain different data types:

 Example

A list with strings, integers and boolean values:

 list1 = ["abc", 34, True, 40, "male"]

type()

 From Python's perspective, lists are defined as objects with the data type 'list':

 <class 'list'>

Example

What is the data type of a list?

 

mylist = ["apple", "banana", "cherry"]

print(type(mylist))

 Output would be: <class 'list'>

 

 The list() Constructor

It is also possible to use the list() constructor when creating a new list.

 Example

Using the list() constructor to make a List:

 mylist = list(("Assam", "Benaras", "Chennai")) # note the double round-brackets


Sunday, January 3, 2021

Python Operators

 

Python Operators

Like all other programming languages, Python has different operators.

  • Arithmetic operators
  • Assignment operators
  • Comparison operators
  • Logical operators
  • Identity operators
  • Membership operators
  • Bitwise operators

Python Arithmetic Operators

Arithmetic operators are used with numeric values to perform common mathematical operations:

Operator

Name

Example

 

+

Addition

x + y

 

-

Subtraction

x - y

 

*

Multiplication

x * y

 

/

Division

x / y

x = 13

y = 3

 

print(x / y)

Result: 4.3333333

%

Modulus

x % y

x = 5

y = 4

print(x % y)

Output: 1

**

Exponentiation

x ** y

x = 2

y = 4

print(x ** y) #same as 2*2*2*2

Output: 16

//

Floor division

x // y

x = 15

y = 2

 

print(x // y)

Output will be 7

 

 

 

Python Assignment Operators

Assignment operators are used to assign values to variables:

Operator

Example

Same As

=

x = 5

x = 5

+=

x += 3

x = x + 3

-=

x -= 3

x = x - 3

*=

x *= 3

x = x * 3

/=

x /= 3

x = x / 3

%=

x %= 3

x = x % 3

//=

x //= 3

x = x // 3

**=

x **= 3

x = x ** 3

&=

x &= 3

x = x & 3

|=

x |= 3

x = x | 3

^=

x ^= 3

x = x ^ 3

>>=

x >>= 3

x = x >> 3

<<=

x <<= 3

x = x << 3



Python Comparison Operators

Comparison operators are used to compare two values:

Operator

Name

Example

==

Equal

x == y

!=

Not equal

x != y

> 

Greater than

x > y

< 

Less than

x < y

>=

Greater than or equal to

x >= y

<=

Less than or equal to

x <= y


Python Logical Operators

Logical operators are used to combine conditional statements:

Operator

Description

Example

and 

Returns True if both statements are true

x < 5 and  x < 10

or

Returns True if one of the statements is true

x < 5 or x < 4

not

Reverse the result, returns False if the result is true

not(x < 5 and x < 10)


Python Identity Operators

Identity operators are used to compare the objects, not if they are equal, but if they are actually the same object, with the same memory location:

Operator

Description

Example

is 

Returns True if both variables are the same object

x is y

 

x = ["Delhi", "India"]

y = ["Delhi", "India"]

z = x

print(x is z)

 

# returns True because z is the same object as x

 

print(x is y)

 

# returns False because x is not the same object as y, even if they have the same content

 

print(x == y)

 

# to demonstrate the difference betweeen "is" and "==": this comparison returns True because x is equal to y

is not

Returns True if both variables are not the same object

x is not y

 

x = ["Delhi", "India"]

y = ["Delhi", "India"]

z = x

 

print(x is not z)

 

# returns False because z is the same object as x

 

print(x is not y)

 

# returns True because x is not the same object as y, even if they have the same content

 

print(x != y)

 

# to demonstrate the difference between "is not" and "!=": this comparison returns False because x is equal to y


Python Membership Operators

Membership operators are used to test if a sequence is presented in an object:

Operator

Description

Example

in 

Returns True if a sequence with the specified value is present in the object

x in y

 

x = ["Delhi", "India"]

 

print("India" in x)

 

# returns True because a sequence with the value "India" is in the list

not in

Returns True if a sequence with the specified value is not present in the object

x not in y

 

x = ["Delhi", "India"]

 

print("Dhaka" not in x)

 

# returns false because a sequence with the value "Dhaka" is not in the list


Python Bitwise Operators

Bitwise operators are used to compare (binary) numbers:

Operator

Name

Description

AND

Sets each bit to 1 if both bits are 1

|

OR

Sets each bit to 1 if one of two bits is 1

 ^

XOR

Sets each bit to 1 if only one of two bits is 1

NOT

Inverts all the bits

<< 

Zero fill left shift

Shift left by pushing zeros in from the right and let the leftmost bits fall off

>> 

Signed right shift

Shift right by pushing copies of the leftmost bit in from the left, and let the rightmost bits fall off

 


Subscribe via email

Enter your email address:

Delivered by FeedBurner