Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
204 views

List Vs Mutability:: Once We Creates A List Object, We Can Modify Its Content. Hence List Objects Are Mutable. Eg

The document discusses lists in Python. It covers: 1) Lists are mutable - their contents can be modified. Common operations like append(), insert(), pop() are demonstrated. 2) Traversing lists using for loops and while loops to access each element. 3) Important list functions like len(), count(), index() for getting information about lists. 4) Manipulating list elements using functions like append(), insert(), extend(), remove(), pop(). 5) Ordering list elements using reverse(), sort().

Uploaded by

Niranjan
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
204 views

List Vs Mutability:: Once We Creates A List Object, We Can Modify Its Content. Hence List Objects Are Mutable. Eg

The document discusses lists in Python. It covers: 1) Lists are mutable - their contents can be modified. Common operations like append(), insert(), pop() are demonstrated. 2) Traversing lists using for loops and while loops to access each element. 3) Important list functions like len(), count(), index() for getting information about lists. 4) Manipulating list elements using functions like append(), insert(), extend(), remove(), pop(). 5) Ordering list elements using reverse(), sort().

Uploaded by

Niranjan
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 100

7)

8) Output
9) D:\Python_classes>py test.py
10) [3, 5, 7]
11) [5, 7, 9]
12) [4, 5, 6, 7]
13) [9, 7, 5]
14) [5, 6, 7, 8, 9, 10]

List vs mutability:
Once we creates a List object,we can modify its content. Hence List objects are mutable.

Eg:

1) n=[10,20,30,40]
2) print(n)
3) n[1]=777
4) print(n)
5)
6) D:\Python_classes>py test.py
7) [10, 20, 30, 40]
8) [10, 777, 30, 40]

Traversing the elements of List:


The sequential access of each element in the list is called traversal.

1. By using while loop:

1) n=[0,1,2,3,4,5,6,7,8,9,10]
2) i=0
3) while i<len(n):
4)print(n[i])
5)i=i+1
6)

8) D:\Python_classes>py
7) 0 test.py 9) 1
11) 3
10) 2
13) 5
12) 4
15) 7
14) 6
17) 9
16) 8
18) 10

2. By using for loop:


1) n=[0,1,2,3,4,5,6,7,8,9,10]
2) for n1 in n:
3) print(n1)
4)
5) D:\Python_classes>py test.py
6) 0
7) 1
8) 2
9) 3
10) 4
11) 5
12) 6
13) 7
14) 8
15) 9
16) 10

3. To display only even numbers:


1) n=[0,1,2,3,4,5,6,7,8,9,10]
2) for n1 in n:
3) if n1%2==0:
4) print(n1)
5)
6) D:\Python_classes>py test.py
7) 0
8) 2
9) 4
10) 6
11) 8
12) 10

4. To display elements by index wise:


1) l=["A","B","C"]
2) x=len(l)
3) for i in range(x):
4) print(l[i],"is available at positive index: ",i,"and at negative index: ",i-x)
5)
6) Output
7) D:\Python_classes>py test.py
8) A is available at positive index: 0 and at negative index: -3
9) B is available at positive index: 1 and at negative index: -2
10) C is available at positive index: 2 and at negative index: -1
Important functions of List:
I. To get information about list:

1. len():
returns the number of elements present in the list

Eg: n=[10,20,30,40]
print(len(n))==>4

2. count():
It returns the number of occurrences of specified item in the list

1) n=[1,2,2,2,2,3,3]
2) print(n.count(1))
3) print(n.count(2))
4) print(n.count(3))
5) print(n.count(4))
6)
7) Output
8) D:\Python_classes>py test.py
9) 1
10) 4
11) 2
12) 0

3. index() function:

returns the index of first occurrence of the specified item.

Eg:

1) n=[1,2,2,2,2,3,3]
2) print(n.index(1)) ==>0
3) print(n.index(2)) ==>1
4) print(n.index(3)) ==>5
5) print(n.index(4)) ==>ValueError: 4 is not in list

Note: If the specified element not present in the list then we will get ValueError.Hence
before index() method we have to check whether item present in the list or not by using in
operator.
II. Manipulating elements of List:

1. append() function:

We can use append() function to add item at the end of the list.

Eg:

1) list=[]
2) list.append("A")
3) list.append("B")
4) list.append("C")
5) print(list)
6)
7) D:\Python_classes>py test.py
8) ['A', 'B', 'C']

Eg: To add all elements to list upto 100 which are divisible by 10

1) list=[]
2) for i in range(101):
3)if i%10==0:
4) list.append(i)

5)
6)print(list) 7)
9) [0, 10, 20, 30, 40, 50, 60, 70, 80, 90, 100]
8) D:\Python_classes>py test.py

2. insert() function:

To insert item at specified index position

1) n=[1,2,3,4,5]
2) n.insert(1,888)
3) print(n)
4)
5) D:\Python_classes>py test.py
6) [1, 888, 2, 3, 4, 5]

Eg:

1) n=[1,2,3,4,5]
2) n.insert(10,777)
3) n.insert(-10,999)
4) print(n)
5)
6) D:\Python_classes>py test.py
7) [999, 1, 2, 3, 4, 5, 777]

Note: If the specified index is greater than max index then element will be inserted at
last position. If the specified index is smaller than min index then element will be inserted
at first position.

Differences between append() and insert()


append() insert()
In List when we add any element it will In List we can insert any element in
come in last i.e. it will be last element. particular index number

3. extend() function:

To add all items of one list to another list

l1.extend(l2)
all items present in l2 will be added to

l1 Eg:

1) order1=["Chicken","Mutton","Fish"]
2) order2=["RC","KF","FO"]
3) order1.extend(order2)
4) print(order1)
5)
6) D:\Python_classes>py test.py
7) ['Chicken', 'Mutton', 'Fish', 'RC', 'KF', 'FO']

Eg:

1) order=["Chicken","Mutton","Fish"]
2) order.extend("Mushroom")
3) print(order)
4)
5) D:\Python_classes>py test.py
6) ['Chicken', 'Mutton', 'Fish', 'M', 'u', 's', 'h', 'r', 'o', 'o', 'm']

4. remove() function:

We can use this function to remove specified item from the list.If the item present
multiple times then only first occurrence will be removed.
1) n=[10,20,10,30]
2) n.remove(10)
3) print(n)
4)
5) D:\Python_classes>py test.py
6) [20, 10, 30]

If the specified item not present in list then we will get ValueError

1) n=[10,20,10,30]
2) n.remove(40)
3) print(n)
4)
5) ValueError: list.remove(x): x not in list

Note: Hence before using remove() method first we have to check specified element
present in the list or not by using in operator.

5. pop() function:

It removes and returns the last element of the list.


This is only function which manipulates list and returns some element.

Eg:

1) n=[10,20,30,40]
2) print(n.pop())
3) print(n.pop())
4) print(n)
5)
6) D:\Python_classes>py test.py
7) 40
8) 30
9) [10, 20]

If the list is empty then pop() function raises IndexError

Eg:

1) n=[]
2) print(n.pop()) ==> IndexError: pop from empty list
Note:

1. pop() is the only function which manipulates the list and returns some value
2. In general we can use append() and pop() functions to implement stack
datastructure by using list,which follows LIFO(Last In First Out) order.

In general we can use pop() function to remove last element of the list. But we can use to
remove elements based on index.

n.pop(index)===>To remove and return element present at specified index.


n.pop()==>To remove and return last element of the list

1) n=[10,20,30,40,50,60]
2) print(n.pop()) #60
3) print(n.pop(1)) #20
4) print(n.pop(10)) ==>IndexError: pop index out of range

Differences between remove() and pop()

remove() pop()
1) We can use to remove special element 1) We can use to remove last element
from the List. from the List.
2) It can’t return any value. 2) It returned removed element.
3) If special element not available then we 3) If List is empty then we get Error.
get VALUE ERROR.

Note:

List objects are dynamic. i.e based on our requirement we can increase and decrease the
size.

append(),insert() ,extend() ===>for increasing the size/growable nature


remove(), pop() ======>for decreasing the size /shrinking nature
III. Ordering elements of List:

1. reverse():

We can use to reverse() order of elements of list.

1) n=[10,20,30,40]
2) n.reverse()
3) print(n)
4)
5) D:\Python_classes>py test.py
6) [40, 30, 20, 10]

2. sort() function:

In list by default insertion order is preserved. If want to sort the elements of list according
to default natural sorting order then we should go for sort() method.

For numbers ==>default natural sorting order is Ascending Order


For Strings ==> default natural sorting order is Alphabetical Order

1) n=[20,5,15,10,0]
2) n.sort()
3) print(n)#[0,5,10,15,20]
4)
5) s=["Dog","Banana","Cat","Apple"]
6) s.sort()
7)print(s) #['Apple','Banana','Cat','Dog']

Note: To use sort() function, compulsory list should contain only homogeneous elements.
otherwise we will get TypeError

Eg:

1) n=[20,10,"A","B"]
2) n.sort()
3) print(n)
4)
5)TypeError: '<' not supported between instances of 'str' and 'int'

Note: In Python 2 if List contains both numbers and Strings then sort() function first sort
numbers followed by strings

1) n=[20,"B",10,"A"]
2) n.sort()
3) print(n)# [10,20,'A','B']

But in Python 3 it is invalid.

To sort in reverse of default natural sorting order:


We can sort according to reverse of default natural sorting order by using reverse=True
argument.

Eg:

1. n=[40,10,30,20]
2. n.sort()
3. print(n) ==>[10,20,30,40]
4. n.sort(reverse=True)
5. print(n) ===>[40,30,20,10]
6. n.sort(reverse=False)
7. print(n) ==>[10,20,30,40]

Aliasing and Cloning of List objects:


The process of giving another reference variable to the existing list is called aliasing.

Eg:

1) x=[10,20,30,40]
2) y=x 10 20 30 40
3) print(id(x)) x
4)print(id(y
y
))

The problem in this approach is by using one reference variable if we are changing
content,then those changes will be reflected to the other reference variable.

1) x=[10,20,30,40]
2) y=x 10 20 30 40
3) y[1]=777 x 777
4) print(x) ==>[10,777,30,40] y

To overcome this problem we should go for cloning.


The process of creating exactly duplicate independent object is called cloning.

We can implement cloning by using slice operator or by using copy() function


1. By using slice operator:

1) x=[10,20,30,40]
2) y=x[:]
3) y[1]=777
4) print(x) ==>[10,20,30,40]
5) print(y) ==>[10,777,30,40]

10 20 30 40
x

10 20 30 40
777
y

2. By using copy() function:

1) x=[10,20,30,40]
2) y=x.copy()
3) y[1]=777
4) print(x) ==>[10,20,30,40]
5) print(y) ==>[10,777,30,40]

10 20 30 40
x

10 20 30 40
777
y

Q. Difference between = operator and copy() function

= operator meant for aliasing


copy() function meant for cloning
Using Mathematical operators for List Objects:
We can use + and * operators for List objects.

1. Concatenation operator(+):

We can use + to concatenate 2 lists into a single list

1) a=[10,20,30]
2) b=[40,50,60]
3) c=a+b
4) print(c) ==>[10,20,30,40,50,60]

Note: To use + operator compulsory both arguments should be list objects,otherwise we


will get TypeError.

Eg:

c=a+40 ==>TypeError: can only concatenate list (not "int") to


list c=a+[40] ==>valid

2. Repetition Operator(*):

We can use repetition operator * to repeat elements of list specified number of times

Eg:

1) x=[10,20,30]
2) y=x*3
3) print(y)==>[10,20,30,10,20,30,10,20,30]

Comparing List objects


We can use comparison operators for List objects.

Eg:

1. x=["Dog","Cat","Rat"]
2. y=["Dog","Cat","Rat"]
3. z=["DOG","CAT","RAT"]
4. print(x==y) True
5. print(x==z) False
6. print(x != z) True
Note:

Whenever we are using comparison operators(==,!=) for List objects then the following
should be considered
1. The number of elements
2. The order of elements
3. The content of elements (case sensitive)

Note: When ever we are using relatational operators(<,<=,>,>=) between List objects,only
first element comparison will be performed.

Eg:

1. x=[50,20,30]
2. y=[40,50,60,100,200]
3. print(x>y) True
4. print(x>=y) True
5. print(x<y) False
6. print(x<=y) False

Eg:

1. x=["Dog","Cat","Rat"]
2. y=["Rat","Cat","Dog"]
3. print(x>y) False
4. print(x>=y) False
5. print(x<y) True
6. print(x<=y) True

Membership operators:
We can check whether element is a member of the list or not by using memebership
operators.

in operator
not in operator

Eg:

1. n=[10,20,30,40]
2. print (10 in n)
3. print (10 not in n)
4. print (50 in n)
5. print (50 not in n)
6.
7. Output
8. True
9. False
10. False
11. True

clear() function:

We can use clear() function to remove all elements of List.

Eg:

1. n=[10,20,30,40]
2. print(n)
3. n.clear()
4. print(n)
5.
6. Output
7. D:\Python_classes>py test.py
8. [10, 20, 30, 40]
9. []

Nested Lists:
Sometimes we can take one list inside another list. Such type of lists are called nested
lists.

Eg:

1. n=[10,20,[30,40]]
2. print(n)
3. print(n[0])
4. print(n[2])
5. print(n[2][0])
6. print(n[2][1])
7.
8. Output
9. D:\Python_classes>py test.py
10. [10, 20, [30, 40]]
11. 10
12. [30, 40]
13. 30
14. 40

Note: We can access nested list elements by using index just like accessing multi
dimensional array elements.
Nested List as Matrix:
In Python we can represent matrix by using nested lists.

1) n=[[10,20,30],[40,50,60],[70,80,90]]
2) print(n)
3) print("Elements by Row wise:")
4) for r in n:
5) print(r)
6) print("Elements by Matrix style:")
7) for i in range(len(n)):
8) for j in range(len(n[i])):
9) print(n[i][j],end=' ')
10) print()
11)
12) Output
13) D:\Python_classes>py test.py
14) [[10, 20, 30], [40, 50, 60], [70, 80, 90]]
15) Elements by Row wise:
16) [10, 20, 30]
17) [40, 50, 60]
18) [70, 80, 90]
19) Elements by Matrix style:
20) 10 20 30
21) 40 50 60
22) 70 80 90

List Comprehensions:
It is very easy and compact way of creating list objects from any iterable objects(like
list,tuple,dictionary,range etc) based on some condition.

Syntax:
list=[expression for item in list if condition]

Eg:

1) s=[ x*x for x in range(1,11)]


2) print(s)
3) v=[2**x for x in range(1,6)]
4) print(v)
5) m=[x for x in s if x%2==0]
6) print(m)
7)
8) Output
9) D:\Python_classes>py test.py
10) [1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
11) [2, 4, 8, 16, 32]
12) [4, 16, 36, 64, 100]

Eg:

1) words=["Balaiah","Nag","Venkatesh","Chiranjeevi"]
2) l=[w[0] for w in words]
3) print(l)
4)
5) Output['B', 'N', 'V', 'C']

Eg:

1) num1=[10,20,30,40]
2) num2=[30,40,50,60]
3) num3=[ i for i in num1 if i not in num2]
4) print(num3) [10,20]
5)
6) common elements present in num1 and num2
7) num4=[i for i in num1 if i in num2]
8) print(num4) [30, 40]

Eg:

1) words="the quick brown fox jumps over the lazy dog".split()


2) print(words)
3) l=[[w.upper(),len(w)] for w in words]
4) print(l)
5)
6) Output
7) ['the', 'quick', 'brown', 'fox', 'jumps', 'over', 'the', 'lazy', 'dog']
8) [['THE', 3], ['QUICK', 5], ['BROWN', 5], ['FOX', 3], ['JUMPS', 5], ['OVER', 4],
9) ['THE', 3], ['LAZY', 4], ['DOG', 3]]

Q. Write a program to display unique vowels present in the given word?

1) vowels=['a','e','i','o','u']
2) word=input("Enter the word to search for vowels: ")
3) found=[]
4) for letter in word:
5) if letter in vowels:
6) if letter not in found:
7) found.append(letter)
8) print(found)
9) print("The number of different vowels present in",word,"is",len(found))
10)
11)
12) D:\Python_classes>py test.py
13) Enter the word to search for vowels: Digitsoftwaresolutions
14) ['u', 'a', 'o', 'e', 'i']
15) The number of different vowels present in Digitsoftwaresolutions is 5

list out all functions of list and write a program to use these functions
Tuple Data Structure
1. Tuple is exactly same as List except that it is immutable. i.e once we creates
Tuple object,we cannot perform any changes in that object.
Hence Tuple is Read Only version of List.
2. If our data is fixed and never changes then we should go for Tuple.
3. Insertion Order is preserved
4. Duplicates are allowed
5. Heterogeneous objects are allowed.
6. We can preserve insertion order and we can differentiate duplicate objects by using
index. Hence index will play very important role in Tuple also.
Tuple support both +ve and -ve index. +ve index means forward direction(from left to
right) and -ve index means backward direction(from right to left)
7. We can represent Tuple elements within Parenthesis and with comma
seperator. Parenethesis are optional but recommended to use.

Eg:

1. t=10,20,30,40
2. print(t)
3. print(type(t))
4.
5. Output
6. (10, 20, 30, 40)
7. <class 'tuple'>
8.
9. t=()
10. print(type(t)) # tuple

Note: We have to take special care about single valued tuple.compulsary the value
should ends with comma,otherwise it is not treated as tuple.
Eg:

1. t=(10)
2. print(t)
3. print(type(t))
4.
5. Output
6. 10
7. <class 'int'>
Eg:

1. t=(10,)
2. print(t)
3. print(type(t))
4.
5. Output
6. (10,)
7. <class 'tuple'>

Q. Which of the following are valid tuples?

1. t=()
2. t=10,20,30,40
3. t=10
4. t=10,
5. t=(10)
6. t=(10,)
7.t=(10,20,30,40)

Tuple creation:

1. t=()
creation of empty tuple

2. t=(10,)
t=10,
creation of single valued tuple ,parenthesis are optional,should ends with comma

3. t=10,20,30
t=(10,20,30)
creation of multi values tuples & parenthesis are optional

4. By using tuple() function:


1. list=[10,20,30]
2. t=tuple(list)
3. print(t)
4.
5. t=tuple(range(10,20,2))
6. print(t)
Accessing elements of tuple:
We can access either by index or by slice operator

1. By using index:
1. t=(10,20,30,40,50,60)
2. print(t[0]) #10
3. print(t[-1]) #60
4. print(t[100]) IndexError: tuple index out of range

2. By using slice operator:

1. t=(10,20,30,40,50,60)
2. print(t[2:5])
3. print(t[2:100])
4. print(t[::2])
5.
6. Output
7. (30, 40, 50)
8. (30, 40, 50, 60)
9. (10, 30, 50)

Tuple vs immutability:
Once we creates tuple,we cannot change its content.
Hence tuple objects are immutable.

Eg:
t=(10,20,30,40)
t[1]=70 TypeError: 'tuple' object does not support item assignment

Mathematical operators for tuple:


We can apply + and * operators for tuple

1. Concatenation Operator(+):
1. t1=(10,20,30)
2. t2=(40,50,60)
3. t3=t1+t2
4. print(t3) # (10,20,30,40,50,60)
2. Multiplication operator or repetition operator(*)

1. t1=(10,20,30)
2. t2=t1*3
3. print(t2) #(10,20,30,10,20,30,10,20,30)

Important functions of Tuple:

1. len()
To return number of elements present in the tuple

Eg:
t=(10,20,30,40)
print(len(t)) #4

2. count()
To return number of occurrences of given element in the tuple

Eg:
t=(10,20,10,10,20)
print(t.count(10)) #3

3. index()
returns index of first occurrence of the given element.
If the specified element is not available then we will get ValueError.

Eg:
t=(10,20,10,10,20)
print(t.index(10)) #0
print(t.index(30)) ValueError: tuple.index(x): x not in tuple

4. sorted()
To sort elements based on default natural sorting order

1. t=(40,10,30,20)
2. t1=sorted(t)
3. print(t1)
4. print(t)
5.
6. Output
7. [10, 20, 30, 40]
8. (40, 10, 30, 20)

We can sort according to reverse of default natural sorting order as follows


t1=sorted(t,reverse=True)
print(t1) [40, 30, 20, 10]

5. min() and max() functions:

These functions return min and max values according to default natural sorting order.

Eg:

1. t=(40,10,30,20)
2. print(min(t)) #10
3. print(max(t)) #40

6. cmp():

It compares the elements of both tuples.


If both tuples are equal then returns 0
If the first tuple is less than second tuple then it returns -1
If the first tuple is greater than second tuple then it returns +1

Eg:

1. t1=(10,20,30)
2. t2=(40,50,60)
3. t3=(10,20,30)
4. print(cmp(t1,t2)) # -1
5. print(cmp(t1,t3)) # 0
6. print(cmp(t2,t3)) # +1

Note: cmp() function is available only in Python2 but not in Python 3

Tuple Packing and Unpacking:


We can create a tuple by packing a group of variables.

Eg:

a=10
b=20
c=30
d=40
t=a,b,c,d
print(t) #(10, 20, 30, 40)

Here a,b,c,d are packed into a tuple t. This is nothing but tuple packing.
Tuple unpacking is the reverse process of tuple packing
We can unpack a tuple and assign its values to different variables

Eg:

1. t=(10,20,30,40)
2. a,b,c,d=t
3. print("a=",a,"b=",b,"c=",c,"d=",d)
4.
5. Output
6. a= 10 b= 20 c= 30 d= 40

Note: At the time of tuple unpacking the number of variables and number of
values should be same. ,otherwise we will get ValueError.

Eg:
t=(10,20,30,40)
a,b,c=t #ValueError: too many values to unpack (expected 3)

Tuple Comprehension:
Tuple Comprehension is not supported by Python.

t= ( x**2 for x in range(1,6))

Here we are not getting tuple object and we are getting generator object.

1. t= ( x**2 for x in range(1,6))


2. print(type(t))
3. for x in t:
4. print(x)
5.
6. Output
7. D:\Python_classes>py test.py
8. <class 'generator'>
9. 1
10. 4
11. 9
12. 16
13. 25
Q. Write a program to take a tuple of numbers from the keyboard and print its sum and
average?

1. t=eval(input("Enter Tuple of Numbers:"))


2. l=len(t)
3. sum=0
4. for x in t:
5.sum=sum+x
6. print("The Sum=",sum)
7. print("The Average=",sum/l)
8.
9. D:\Python_classes>py test.py
10. Enter Tuple of Numbers:(10,20,30,40)

12. The
11. The Sum=
Average=
100 25.0
13.
15. Enter Tuple of Numbers:(100,200,300)
14. D:\Python_classes>py test.py
17. The Average= 200.0
16. The Sum= 600

Differences between List and Tuple:


List and Tuple are exactly same except small difference: List objects are mutable where as
Tuple objects are immutable.

In both cases insertion order is preserved, duplicate objects are allowed, heterogenous
objects are allowed, index and slicing are supported.

List Tuple
1) List is a Group of Comma separeated 1) Tuple is a Group of Comma separeated
Values within Square Brackets and Square Values within Parenthesis and Parenthesis
Brackets are mandatory. are optional.
Eg: i = [10, 20, 30, 40] Eg: t = (10, 20, 30, 40)
t = 10, 20, 30, 40
2) List Objects are Mutable i.e. once we 2) Tuple Objeccts are Immutable i.e. once
creates List Object we can perform any we creates Tuple Object we cannot change
changes in that Object. its content.
Eg: i[1] = 70 t[1] = 70  ValueError: tuple object does
not support item assignment.
3) If the Content is not fixed and keep on 3) If the content is fixed and never changes
changing then we should go for List. then we should go for Tuple.
4) List Objects can not used as Keys for 4) Tuple Objects can be used as Keys for
Dictionries because Keys should be Dictionries because Keys should be
Hashable and Immutable. Hashable and Immutable.

nd
DIGITSOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
7
Set Data Structure
 If we want to represent a group of unique values as a single entity then we should
go for set.
 Duplicates are not allowed.
 Insertion order is not preserved.But we can sort the elements.
 Indexing and slicing not allowed for the set.
 Heterogeneous elements are allowed.
 Set objects are mutable i.e once we creates set object we can perform any changes
in that object based on our requirement.
 We can represent set elements within curly braces and with comma seperation
 We can apply mathematical operations like union,intersection,difference etc on set
objects.

Creation of Set objects:


Eg:

1. s={10,20,30,40}
2. print(s)
3. print(type(s))
4.
5. Output
6. {40, 10, 20, 30}
7. <class 'set'>

We can create set objects by using set() function

s=set(any sequence)

Eg 1:

1. l = [10,20,30,40,10,20,10]
2. s=set(l)
3. print(s) # {40, 10, 20, 30}

Eg 2:

1. s=set(range(5))
2. print(s) #{0, 1, 2, 3, 4}

Note: While creating empty set we have to take special care.


Compulsory we should use set() function.
s={} ==>It is treated as dictionary but not empty set.

Eg:

1. s={}
2. print(s)
3. print(type(s))
4.
5. Output
6. {}
7. <class 'dict'>

Eg:

1. s=set()
2. print(s)
3. print(type(s))
4.
5. Output
6. set()
7. <class 'set'>

Important functions of set:


1. add(x):

Adds item x to the set

Eg:

1. s={10,20,30}
2. s.add(40);
3. print(s) #{40, 10, 20, 30}

2. update(x,y,z):

To add multiple items to the set.


Arguments are not individual elements and these are Iterable objects like List,range etc.
All elements present in the given Iterable objects will be added to the set.

Eg:

1. s={10,20,30}
2. l=[40,50,60,10]
3. s.update(l,range(5))
4. print(s)
5.
6. Output
7. {0, 1, 2, 3, 4, 40, 10, 50, 20, 60, 30}

Q. What is the difference between add() and update() functions in set?

We can use add() to add individual item to the Set,where as we can use update() function
to add multiple items to Set.
add() function can take only one argument where as update() function can take any
number of arguments but all arguments should be iterable objects.

Q. Which of the following are valid for set s?

1. s.add(10)
2. s.add(10,20,30) TypeError: add() takes exactly one argument (3 given)
3. s.update(10) TypeError: 'int' object is not
iterable 4. s.update(range(1,10,2),range(0,10,2))

3. copy():

Returns copy of the set.


It is cloned object.

s={10,20,30}
s1=s.copy()
print(s1)

4. pop():

It removes and returns some random element from the set.

Eg:

1. s={40,10,30,20}
2. print(s)
3. print(s.pop())
4. print(s)
5.
6. Output
7. {40, 10, 20, 30}
8. 40
9. {10, 20, 30}
5. remove(x):

It removes specified element from the set.


If the specified element not present in the Set then we will get KeyError

s={40,10,30,20}
s.remove(30)
print(s) # {40, 10, 20}
s.remove(50) ==>KeyError: 50

6. discard(x):

It removes the specified element from the set.


If the specified element not present in the set then we won't get any error.

s={10,20,30}
s.discard(10)
print(s) ===>{20, 30}
s.discard(50)
print(s) ==>{20, 30}

Q. What is the difference between remove() and discard() functions in Set?


Q. Explain differences between pop(),remove() and discard() functionsin Set?

7.clear():

To remove all elements from the Set.

1. s={10,20,30}
2. print(s)
3. s.clear()
4. print(s)
5.
6. Output
7. {10, 20, 30}
8. set()
Mathematical operations on the Set:
1. union():

x.union(y) ==>We can use this function to return all elements present in both sets

x.union(y) or x|y

Eg:
x={10,20,30,40}
y={30,40,50,60}
print(x.union(y)) #{10, 20, 30, 40, 50, 60}
print(x|y) #{10, 20, 30, 40, 50, 60}

2. intersection():

x.intersection(y) or x&y

Returns common elements present in both x and y

Eg:

x={10,20,30,40}
y={30,40,50,60}
print(x.intersection(y)) #{40, 30}
print(x&y) #{40, 30}

3. difference():

x.difference(y) or x-y
returns the elements present in x but not in y

Eg:

x={10,20,30,40}
y={30,40,50,60}
print(x.difference(y)) #{10, 20}
print(x-y) #{10, 20}
print(y-x) #{50, 60}
4. symmetric_difference():

x.symmetric_difference(y) or x^y

Returns elements present in either x or y but not in both

Eg:

x={10,20,30,40}
y={30,40,50,60}
print(x.symmetric_difference(y)) #{10, 50, 20, 60}
print(x^y) #{10, 50, 20, 60}

Membership operators: (in , not in)


Eg:

1. s=set("Digit")
2. print(s)
3. print('d' in s)
4. print('z' in s)
5.
6. Output
7. {'u', 'g', 'r', 'd', 'a'}
8. True
9. False

Set Comprehension:
Set comprehension is possible.

s={x*x for x in
range(5)} print(s) #{0, 1,
4, 9, 16}

s={2**x for x in range(2,10,2)}


print(s) #{16, 256, 64, 4}

set objects won't support indexing and slicing:


Eg:
s={10,20,30,40}
print(s[0]) ==>TypeError: 'set' object does not support
indexing print(s[1:3]) ==>TypeError: 'set' object is not
subscriptable
Q.Write a program to eliminate duplicates present in the list?

Approach-1:

1. l=eval(input("Enter List of values: "))


2. s=set(l)
3. print(s)
4.
5. Output
6. D:\Python_classes>py test.py
7. Enter List of values: [10,20,30,10,20,40]
8. {40, 10, 20, 30}

Approach-2:

1. l=eval(input("Enter List of values: "))


2. l1=[]
3. for x in l:
4. if x not in l1:
5. l1.append(x)
6. print(l1)
7.
8. Output
9. D:\Python_classes>py test.py
10. Enter List of values: [10,20,30,10,20,40]
11. [10, 20, 30, 40]

Q. Write a program to print different vowels present in the given word?


1. w=input("Enter word to search for vowels: ")
2. s=set(w)
3. v={'a','e','i','o','u'}
4. d=s.intersection(v)
5. print("The different vowel present in",w,"are",d)
6.
7. Output
8. D:\Python_classes>py test.py
9. Enter word to search for vowels: Digit
10. The different vowel present in Digit are {'u', 'a'}
Dictionary Data Structure
We can use List,Tuple and Set to represent a group of individual objects as a single entity.

If we want to represent a group of objects as key-value pairs then we should go for


Dictionary.

Eg:
rollno- - -name
phone number--address
ipaddress- -domain name

Duplicate keys are not allowed but values can be duplicated.


Hetrogeneous objects are allowed for both key and values.
insertion order is not preserved
Dictionaries are mutable
Dictionaries are dynamic
indexing and slicing concepts are not applicable

Note: In C++ and Java Dictionaries are known as "Map" where as in Perl and Ruby it is
known as "Hash"

How to create Dictionary?


d={} or d=dict()
we are creating empty dictionary. We can add entries as follows

d[100]="Digit"
d[200]="ravi"
d[300]="shiva"
print(d) #{100: 'Digit', 200: 'ravi', 300: 'shiva'}

If we know data in advance then we can create dictionary as follows

d={100:'Digit' ,200:'ravi', 300:'shiva'}

d={key:value, key:value}
How to access data from the dictionary?
We can access data by using keys.

d={100:'Digit' ,200:'ravi', 300:'shiva'}


print(d[100]) #Digit
print(d[300]) #shiva

If the specified key is not available then we will get KeyError

print(d[400]) # KeyError: 400

We can prevent this by checking whether key is already available or not by using
has_key() function or by using in operator.

d.has_key(400) ==> returns 1 if key is available otherwise returns 0

But has_key() function is available only in Python 2 but not in Python 3. Hence
compulsory we have to use in operator.

if 400 in d:
print(d[400])

Q. Write a program to enter name and percentage marks in a dictionary and


display information on the screen
1) rec={}
2) n=int(input("Enter number of students: "))
3) i=1
4) while i <=n:
5) name=input("Enter Student Name: ")
6) marks=input("Enter % of Marks of Student: ")
7) rec[name]=marks
8) i=i+1
9) print("Name of Student","\t","% of marks")
10) for x in rec:
11) print("\t",x,"\t\t",rec[x])
12)
13) Output
14) D:\Python_classes>py test.py
15) Enter number of students: 3
16) Enter Student Name: Digit
17) Enter % of Marks of Student: 60%
18) Enter Student Name: ravi
19) Enter % of Marks of Student: 70%
20) Enter Student Name: shiva
21) Enter % of Marks of Student: 80%
22) Name of Student % of marks
23) Digit 60%
24) ravi 70 %
25) shiva 80%

How to update dictionaries?


d[key]=value

If the key is not available then a new entry will be added to the dictionary with the
specified key-value pair

If the key is already available then old value will be replaced with new value.

Eg:

1. d={100:"Digit",200:"ravi",300:"shiva"}
2. print(d)
3. d[400]="pavan"
4. print(d)
5. d[100]="sunny"
6. print(d)
7.
8. Output
9. {100: 'Digit', 200: 'ravi', 300: 'shiva'}
10. {100: 'Digit', 200: 'ravi', 300: 'shiva', 400: 'pavan'}
11. {100: 'sunny', 200: 'ravi', 300: 'shiva', 400: 'pavan'}

How to delete elements from dictionary?


del d[key]

It deletes entry associated with the specified key.


If the key is not available then we will get
KeyError

Eg:

1. d={100:"Digit",200:"ravi",300:"shiva"}
2. print(d)
3. del d[100]
4. print(d)
5. del d[400]
6.
7. Output
8. {100: 'Digit', 200: 'ravi', 300: 'shiva'}
9. {200: 'ravi', 300: 'shiva'}
10. KeyError: 400

d.clear()

To remove all entries from the dictionary

Eg:

1. d={100:"Digit",200:"ravi",300:"shiva"}
2. print(d)
3. d.clear()
4. print(d)
5.
6. Output
7. {100: 'Digit', 200: 'ravi', 300: 'shiva'}
8. {}

del d

To delete total dictionary.Now we cannot access d

Eg:

1. d={100:"Digit",200:"ravi",300:"shiva"}
2. print(d)
3. del d
4. print(d)
5.
6. Output
7. {100: 'Digit', 200: 'ravi', 300: 'shiva'}
8. NameError: name 'd' is not defined

Important functions of dictionary:


1. dict():

To create a dictionary

d=dict() ===>It creates empty dictionary


d=dict({100:"Digit",200:"ravi"}) ==>It creates dictionary with specified elements
d=dict([(100,"Digit"),(200,"shiva"),(300,"ravi")])==>It creates dictionary with the given
list of tuple elements
2. len()

Returns the number of items in the dictionary

3. clear():

To remove all elements from the dictionary

4. get():

To get the value associated with the key

d.get(key)
If the key is available then returns the corresponding value otherwise returns None.It
wont raise any error.

d.get(key,defaultvalue)
If the key is available then returns the corresponding value otherwise returns default
value.

Eg:

d={100:"Digit",200:"ravi",300:"shiva"}
print(d[100]) ==>Digit
print(d[400]) ==>KeyError:400
print(d.get(100)) ==Digit
print(d.get(400)) ==>None
print(d.get(100,"Guest")) ==Digit
print(d.get(400,"Guest")) ==>Guest

3. pop():

d.pop(key)
It removes the entry associated with the specified key and returns the corresponding
value
If the specified key is not available then we will get KeyError

Eg:

1) d={100:"Digit",200:"ravi",300:"shiva"}
2) print(d.pop(100))
3) print(d)
4) print(d.pop(400))
5)
6) Output
7) Digit
8) {200: 'ravi', 300: 'shiva'}
9) KeyError: 400

4. popitem():

It removes an arbitrary item(key-value) from the dictionaty and returns it.

Eg:

1) d={100:"Digit",200:"ravi",300:"shiva"}
2) print(d)
3) print(d.popitem())
4) print(d)
5)
6) Output
7) {100: 'Digit', 200: 'ravi', 300: 'shiva'}
8) (300, 'shiva')
9) {100: 'Digit', 200: 'ravi'}

If the dictionary is empty then we will get KeyError


d={}
print(d.popitem()) ==>KeyError: 'popitem(): dictionary is empty'

5. keys():

It returns all keys associated eith dictionary

Eg:

1) d={100:"Digit",200:"ravi",300:"shiva"}
2) print(d.keys())
3) for k in d.keys():
4) print(k)
5)
6) Output
7) dict_keys([100, 200, 300])
8) 100
9) 200
10) 300

6. values():

It returns all values associated with the dictionary


Eg:

1. d={100:"Digit",200:"ravi",300:"shiva"}
2. print(d.values())
3. for v in d.values():
4. print(v)
5.
6. Output
7. dict_values(['Digit', 'ravi', 'shiva'])
8. Digit
9. ravi
10. shiva

7. items():

It returns list of tuples representing key-value pairs.

[(k,v),(k,v),(k,v)]

Eg:

1. d={100:"Digit",200:"ravi",300:"shiva"}
2. for k,v in d.items():
3. print(k,"--",v)
4.
5. Output
6. 100 -- Digit
7. 200 -- ravi
8. 300 -- shiva

8. copy():

To create exactly duplicate dictionary(cloned copy)

d1=d.copy();

9. setdefault():

d.setdefault(k,v)
If the key is already available then this function returns the corresponding value.
If the key is not available then the specified key-value will be added as new item to the
dictionary.
Eg:

1. d={100:"Digit",200:"ravi",300:"shiva"}
2. print(d.setdefault(400,"pavan"))
3. print(d)
4. print(d.setdefault(100,"sachin"))
5. print(d)
6.
7. Output
8. pavan
9. {100: 'Digit', 200: 'ravi', 300: 'shiva', 400: 'pavan'}
10. Digit
11. {100: 'Digit', 200: 'ravi', 300: 'shiva', 400: 'pavan'}

10. update():

d.update(x)
All items present in the dictionary x will be added to dictionary d

Q. Write a program to take dictionary from the keyboard and print the sum
of values?
1. d=eval(input("Enter dictionary:"))
2. s=sum(d.values())
3. print("Sum= ",s)
4.
5. Output
6. D:\Python_classes>py test.py
7. Enter dictionary:{'A':100,'B':200,'C':300}
8. Sum= 600

Q. Write a program to find number of occurrences of each letter present in


the given string?

1. word=input("Enter any word: ")


2. d={}
3. for x in word:
4. d[x]=d.get(x,0)+1
5. for k,v in d.items():
6. print(k,"occurred ",v," times")
7.
8. Output
9. D:\Python_classes>py test.py
10. Enter any word: mississippi
11. m occurred 1 times
12. i occurred 4 times
13. s occurred 4 times
14. p occurred 2 times

Q. Write a program to find number of occurrences of each vowel present in


the given string?

1.
2. word=input("Enter any word: ") 3. d={}
vowels={'a','e','i','o','u'}
5.if x in vowels:
4. for x in word:

7.
6.for k,v d[x]=d.get(x,0)+1
in sorted(d.items()): 9.
11. D:\Python_classes>py test.py
8.print(k,"occurred ",v," times")
13. a occurred 4 times
10. Output
15. o occurred 2 times
12. Enter any word: doganimaldoganimal

14. i occurred 2 times

Q. Write a program to accept student name and marks from the keyboard
and creates a dictionary. Also display student marks by taking student name
as input?

1) n=int(input("Enter the number of students: "))


2) d={}
3) for i in range(n):
4)name=input("Enter Student Name: ")
5)marks=input("Enter Student Marks: ")
6)d[name]=marks
7) while True:
8)name=input("Enter Student Name to get Marks: ")
9)marks=d.get(name,-1)
10)if marks== -1:
11) print("Student Not Found")
12)else:
13) print("The Marks of",name,"are",marks)
14)option=input("Do you want to find another student marks[Yes|No]")
15)if option=="No":
16) break
17) print("Thanks for using our application")
18)
19) Output
20) D:\Python_classes>py test.py
21) Enter the number of students: 5
22) Enter Student Name: sunny
23) Enter Student Marks: 90
24) Enter Student Name: banny
25) Enter Student Marks: 80
26) Enter Student Name: chinny
27) Enter Student Marks: 70
28) Enter Student Name: pinny
29) Enter Student Marks: 60
30) Enter Student Name: vinny
31) Enter Student Marks: 50
32) Enter Student Name to get Marks: sunny
33) The Marks of sunny are 90
34) Do you want to find another student marks[Yes|No]Yes
35) Enter Student Name to get Marks: Digit
36) Student Not Found
37) Do you want to find another student marks[Yes|No]No
38) Thanks for using our application

Dictionary Comprehension:
Comprehension concept applicable for dictionaries also.

1. squares={x:x*x for x in range(1,6)}


2. print(squares)
3. doubles={x:2*x for x in range(1,6)}
4. print(doubles)
5.
6. Output
7. {1: 1, 2: 4, 3: 9, 4: 16, 5: 25}
8. {1: 2, 2: 4, 3: 6, 4: 8, 5: 10}
FUNCTIONS
If a group of statements is repeatedly required then it is not recommended to write these
statements everytime seperately.We have to define these statements as a single unit and
we can call that unit any number of times based on our requirement without rewriting.
This unit is nothing but function.

The main advantage of functions is code Reusability.


Note: In other languages functions are known as methods,procedures,subroutines etc

Python supports 2 types of functions

1. Built in Functions
2. User Defined Functions

1. Built in Functions:
The functions which are coming along with Python software automatically,are called built
in functions or pre defined functions

Eg:
id()
type()
input()
eval()
etc..

2. User Defined Functions:


The functions which are developed by programmer explicitly according to business
requirements ,are called user defined functions.

Syntax to create user defined functions:

def function_name(parameters) :
""" doc string"""
----
-----
return value
Note: While creating functions we can use 2 keywords
1. def (mandatory)
2. return (optional)

Eg 1: Write a function to print Hello

test.py:
1) def wish():
2) print("Hello Good Morning")
3) wish()
4) wish()
5) wish()

Parameters
Parameters are inputs to the function. If a function contains parameters,then at the time
of calling,compulsory we should provide values otherwise,otherwise we will get error.

Eg: Write a function to take name of the student as input and print wish message by
name.

1. def wish(name):
2. print("Hello",name," Good Morning")

4. wish("Digit")
3. wish("Ravi") 5.
7. D:\Python_classes>py test.py
6.
9.Hello Ravi Good Morning

8. Hello Digit Good Morning

Eg: Write a function to take number as input and print its square value

1. def squareIt(number):
2. print("The Square of",number,"is", number*number)
3. squareIt(4)
4. squareIt(5)
5.
6. D:\Python_classes>py test.py
7. The Square of 4 is 16
8. The Square of 5 is 25
Return Statement:
Function can take input values as parameters and executes business logic, and returns
output to the caller with return statement.

Q. Write a function to accept 2 numbers as input and return sum.


1. def add(x,y):
2. return x+y
3. result=add(10,20)
4. print("The sum is",result)
5. print("The sum is",add(100,200))
6.
7.
8. D:\Python_classes>py test.py
9. The sum is 30
10. The sum is 300

If we are not writing return statement then default return value is None

Eg:

1. def f1():
2. print("Hello")
3. f1()
4. print(f1())
5.
6. Output
7. Hello
8. Hello
9. None

Q. Write a function to check whether the given number is even or odd?


1. def even_odd(num):
2. if num%2==0:
3. print(num,"is Even Number")
4. else:
5. print(num,"is Odd Number")
6. even_odd(10)
7. even_odd(15)
8.
9. Output
10. D:\Python_classes>py test.py
11. 10 is Even Number
12. 15 is Odd Number
Q. Write a function to find factorial of given number?

1) def fact(num):
2)result=1
3)while num>=1:
4) result=result*num
5) num=num-1
6)return result
7) for i in range(1,5):
8)print("The Factorial of",i,"is :",fact(i))
9)
10) Output
11) D:\Python_classes>py test.py
12) The Factorial of 1 is : 1
13) The Factorial of 2 is : 2
14) The Factorial of 3 is : 6
15) The Factorial of 4 is : 24

Returning multiple values from a function:


In other languages like C,C++ and Java, function can return atmost one value. But in
Python, a function can return any number of values.

Eg 1:

1) def sum_sub(a,b):
2)sum=a+b
3)sub=a-b
4)return sum,sub
5) x,y=sum_sub(100,50)
6) print("The Sum is :",x)
7) print("The Subtraction is :",y)
8)
9) Output
10) The Sum is : 150
11) The Subtraction is : 50

Eg 2:

1) def calc(a,b):
2) sum=a+b
3) sub=a-b
4) mul=a*b
5) div=a/b
6) return sum,sub,mul,div
7) t=calc(100,50)
8) print("The Results are")
9) for i in t:
10) print(i)
11)
12) Output
13) The Results are
14) 150
15) 50
16) 5000
17) 2.0

Types of arguments
def f1(a,b):
------
------
------
f1(10,20)

a,b are formal arguments where as 10,20 are actual arguments

There are 4 types are actual arguments are allowed in Python.

1. positional arguments
2. keyword arguments
3. default arguments
4. Variable length arguments

1. positional arguments:

These are the arguments passed to function in correct positional order.

def sub(a,b):
print(a-b)

sub(100,200)
sub(200,100)

The number of arguments and position of arguments must be matched. If we change the
order then result may be changed.

If we change the number of arguments then we will get error.


2. keyword arguments:

We can pass argument values by keyword i.e by parameter name.

Eg:

1. def wish(name,msg):
2. print("Hello",name,msg)
3. wish(name="Digit",msg="Good Morning")
4. wish(msg="Good Morning",name="Digit")
5.
6. Output
7. Hello Digit Good Morning
8. Hello Digit Good Morning

Here the order of arguments is not important but number of arguments must be matched.

Note:

We can use both positional and keyword arguments simultaneously. But first we have to
take positional arguments and then keyword arguments,otherwise we will get
syntaxerror.

def wish(name,msg):
print("Hello",name,msg)
wish("Digit","GoodMorning") ==>valid
wish("Digit",msg="GoodMorning") ==>valid
wish(name="Digit","GoodMorning") ==>invalid SyntaxError:
positional argument follows keyword argument

3. Default Arguments:

Sometimes we can provide default values for our positional arguments.

Eg:

1) def wish(name="Guest"): 3)
2)print("Hello",name,"Good Morning")
5) wish()
4) wish("Digit")
7) Output
6)
9) Hello Guest Good Morning
8) Hello Digit Good Morning
If we are not passing any name then only default value will be considered.

***Note:

After default arguments we should not take non default arguments

def wish(name="Guest",msg="Good Morning"): ===>Valid


def wish(name,msg="Good Morning"): ===>Valid
def wish(name="Guest",msg): ==>Invalid

SyntaxError: non-default argument follows default argument

4. Variable length arguments:

Sometimes we can pass variable number of arguments to our function,such type of


arguments are called variable length arguments.

We can declare a variable length argument with * symbol as follows

def f1(*n):

We can call this function by passing any number of arguments including zero number.
Internally all these values represented in the form of tuple.

Eg:

1) def sum(*n):
2) total=0
3) for n1 in n:
4) total=total+n1
5) print("The Sum=",total)
6)
7) sum()
8) sum(10)
9) sum(10,20)
10) sum(10,20,30,40)
11)
12) Output
13) The Sum= 0
14) The Sum= 10
15) The Sum= 30
16) The Sum= 100

Note:
We can mix variable length arguments with positional arguments.
Eg:

1) def f1(n1,*s):
2)print(n1)

3)for
4) s1 inprint(s1)
s: 5)
7) f1(10,20,30,40)
6) f1(10)
9)
8) f1(10,"A",30,"B")
11) 10
10) Output
13) 20
12) 10
15) 40
14) 30
17) A
16) 10
19) B
18) 30

Note: After variable length argument,if we are taking any other arguments then we
should provide values as keyword arguments.

Eg:

1) def f1(*s,n1):
2) for s1 in s:
3) print(s1)
4) print(n1)
5)
6) f1("A","B",n1=10)
7) Output
8) A
9) B
10) 10

f1("A","B",10) ==>Invalid
TypeError: f1() missing 1 required keyword-only argument: 'n1'

Note: We can declare key word variable length arguments also.


For this we have to use **.

def f1(**n):
We can call this function by passing any number of keyword arguments. Internally these
keyword arguments will be stored inside a dictionary.

Eg:

1) def display(**kwargs):
2) for k,v in kwargs.items():
3) print(k,"=",v)
4) display(n1=10,n2=20,n3=30)
5) display(rno=100,name="Digit",marks=70,subject="Java")
6)
7) Output
8) n1 = 10
9) n2 = 20
10) n3 = 30
11) rno = 100
12) name = Digit
13) marks = 70
14) subject = Java

Case Study:
def f(arg1,arg2,arg3=4,arg4=8):
print(arg1,arg2,arg3,arg4)

1. f(3,2) ==> 3 2 4 8

2. f(10,20,30,40) ===>10 20 30 40

3. f(25,50,arg4=100) ==>25 50 4 100

4. f(arg4=2,arg1=3,arg2=4)===>3 4 4 2
5. f()===>Invalid
TypeError: f() missing 2 required positional arguments: 'arg1' and 'arg2'

6. f(arg3=10,arg4=20,30,40) ==>Invalid
SyntaxError: positional argument follows keyword argument
[After keyword arguments we should not take positional arguments]

7. f(4,5,arg2=6)==>Invalid
TypeError: f() got multiple values for argument 'arg2'

8. f(4,5,arg3=5,arg5=6)==>Invalid
TypeError: f() got an unexpected keyword argument 'arg5'
Note: Function vs Module vs Library:

1. A group of lines with some name is called a function


2. A group of functions saved to a file , is called Module
3. A group of Modules is nothing but Library

Library Function
Module 1Module 2
-----------------
-----------------
Function 1 Function 1 -----------------
-----------------
Function 2 Function 2 -----------------
-----------------
-----------------
Function 3 Function 3 -----------------
-----------------

Types of Variables
Python supports 2 types of variables.

1. Global Variables
2. Local Variables

1. Global Variables

The variables which are declared outside of function are called global variables.
These variables can be accessed in all functions of that module.

Eg:

1) a=10 # global variable


2) def f1():
3)print(a)
4)

5) def f2(): 7)
6)print(a)
9) f2()
8) f1()
11) Output 13) 10
10)

12) 10
2. Local Variables:

The variables which are declared inside a function are called local variables.
Local variables are available only for the function in which we declared it.i.e from outside
of function we cannot access.

Eg:

1) def f1():
2)a=10
3)print(a) # valid
4)
5) def f2():
6)print(a)#invalid
7)
8) f1()
9) f2()
10)
11) NameError: name 'a' is not defined

global keyword:
We can use global keyword for the following 2 purposes:

1. To declare global variable inside function


2. To make global variable available to the function so that we can perform
required modifications

Eg 1:

1) a=10
2) def f1():
3) a=777
4) print(a)
5)
6) def f2():
7) print(a)
8)
9) f1()
10) f2()
11)
12) Output
13) 777
14) 10
Eg 2:

1) a=10
2) def f1():
3)global a
4)a=777
5)print(a)
6)

8)print(a)
7) def f2(): 9)
11) f2()
10) f1()
13) Output 15) 777
12)

14) 777

Eg 3:

1) def f1():
2)a=10
3)print(a)
4)
5) def f2():
6)print(a)
7)
8) f1()
9) f2()
10)
11) NameError: name 'a' is not defined

Eg 4:

1) def f1():
2) global a
3) a=10
4) print(a)
5)
6) def f2():
7) print(a)
8)
9) f1()
10) f2()
11)
12) Output
13) 10
14) 10
Note: If global variable and local variable having the same name then we can access
global variable inside a function as follows

1) a=10#global variable
2) def f1():
3)a=777 #local variable
4)print(a)

6) f1()
5)print(globals()['a']) 7)
9) Output
8)
11) 10
10) 777

Recursive Functions
A function that calls itself is known as Recursive Function.

Eg:
factorial(3)=3*factorial(2)
=3*2*factorial(1)
=3*2*1*factorial(0)
=3*2*1*1
=6
factorial(n)= n*factorial(n-1)

The main advantages of recursive functions are:

1. We can reduce length of the code and improves readability


2. We can solve complex problems very easily.

Q. Write a Python Function to find factorial of given number with recursion.

Eg:

1) def factorial(n):
2) if n==0:
3) result=1
4) else:
5) result=n*factorial(n-1)
6) return result
7) print("Factorial of 4 is :",factorial(4))
8) print("Factorial of 5 is :",factorial(5))
9)
10) Output
11) Factorial of 4 is : 24
12) Factorial of 5 is : 120

Anonymous Functions:
Sometimes we can declare a function without any name,such type of nameless functions
are called anonymous functions or lambda functions.

The main purpose of anonymous function is just for instant use(i.e for one time usage)

Normal Function:
We can define by using def keyword.
def squareIt(n):
return n*n

lambda Function:
We can define by using lambda keyword

lambda n:n*n

Syntax of lambda Function:


lambda argument_list : expression

Note: By using Lambda Functions we can write very concise code so that readability of
the program will be improved.

Q. Write a program to create a lambda function to find square of given


number?

1) s=lambda n:n*n
2) print("The Square of 4 is :",s(4))
3) print("The Square of 5 is :",s(5))
4)
5) Output
6) The Square of 4 is : 16
7) The Square of 5 is : 25

Q. Lambda function to find sum of 2 given numbers

1) s=lambda a,b:a+b
2) print("The Sum of 10,20 is:",s(10,20))
3) print("The Sum of 100,200 is:",s(100,200))
4)
5) Output
6) The Sum of 10,20 is: 30
7) The Sum of 100,200 is: 300

Q. Lambda Function to find biggest of given values.

1)s=lambda a,b:a if a>b else b


2) print("The Biggest of 10,20 is:",s(10,20))
3) print("The Biggest of 100,200 is:",s(100,200))
4)
5) Output
6) The Biggest of 10,20 is: 20
7) The Biggest of 100,200 is: 200

Note:
Lambda Function internally returns expression value and we are not required to write
return statement explicitly.

Note: Sometimes we can pass function as argument to another function. In such cases
lambda functions are best choice.

We can use lambda functions very commonly with filter(),map() and reduce() functions,b'z
these functions expect function as argument.

filter() function:
We can use filter() function to filter values from the given sequence based on some
condition.

filter(function,sequence)

where function argument is responsible to perform conditional check


sequence can be list or tuple or string.

Q. Program to filter only even numbers from the list by using filter()
function?

without lambda Function:


1) def isEven(x):
2) if x%2==0:
3) return True
4) else:
5) return False
6) l=[0,5,10,15,20,25,30]
7) l1=list(filter(isEven,l))
8) print(l1) #[0,10,20,30]

with lambda Function:


1) l=[0,5,10,15,20,25,30]
2) l1=list(filter(lambda x:x%2==0,l))
3) print(l1) #[0,10,20,30]
4) l2=list(filter(lambda x:x%2!=0,l))
5) print(l2) #[5,15,25]

map() function:
For every element present in the given sequence,apply some functionality and generate
new element with the required modification. For this requirement we should go for
map() function.

Eg: For every element present in the list perform double and generate new list of doubles.

Syntax:

map(function,sequence)

The function can be applied on each element of sequence and generates new sequence.

Eg: Without lambda

1) l=[1,2,3,4,5]
2) def doubleIt(x):
3) return 2*x
4) l1=list(map(doubleIt,l))
5) print(l1) #[2, 4, 6, 8, 10]

with lambda

1) l=[1,2,3,4,5]
2) l1=list(map(lambda x:2*x,l))
3) print(l1) #[2, 4, 6, 8, 10]

-------------------------------------------------------------
Eg 2: To find square of given numbers

1. l=[1,2,3,4,5]
2. l1=list(map(lambda x:x*x,l))
3. print(l1) #[1, 4, 9, 16, 25]

We can apply map() function on multiple lists also.But make sure all list should have same
length.

Syntax: map(lambda x,y:x*y,l1,l2))


x is from l1 and y is from
l2
Eg:

1. l1=[1,2,3,4]
2. l2=[2,3,4,5]
3. l3=list(map(lambda x,y:x*y,l1,l2))
4. print(l3) #[2, 6, 12, 20]

reduce() function:
reduce() function reduces sequence of elements into a single element by applying the
specified function.

reduce(function,sequence)

reduce() function present in functools module and hence we should write import
statement.

Eg:

1) from functools import *


2) l=[10,20,30,40,50]
3) result=reduce(lambda x,y:x+y,l)
4) print(result) # 150

Eg:

1) result=reduce(lambda x,y:x*y,l)
2) print(result) #12000000

Eg:

1) from functools import *


2) result=reduce(lambda x,y:x+y,range(1,101))
3) print(result) #5050
Note:
 In Python every thing is treated as object.
 Even functions also internally treated as objects only.

Eg:

1) def f1():
2) print("Hello")
3) print(f1)
4) print(id(f1))

Output
<function f1 at 0x00419618>
4298264

Function Aliasing:
For the existing function we can give another name, which is nothing but function aliasing.

Eg:

1) def wish(name):
2) print("Good Morning:",name)
3)
4) greeting=wish
5) print(id(wish))
6) print(id(greeting))
7)
8) greeting('Digit')
9) wish('Digit')

Output
4429336
4429336
Good Morning: Digit
Good Morning: Digit

Note: In the above example only one function is available but we can call that function by using
either wish name or greeting name.

If we delete one name still we can access that function by using alias name

Eg:

1) def wish(name):
2) print("Good Morning:",name)
3)
4) greeting=wish
5)
6) greeting('Digit')
7) wish('Digit')
8)
9) del wish
10) #wish('Digit') ==>NameError: name 'wish' is not defined
11) greeting('Pavan')

Output
Good Morning: Digit
Good Morning: Digit
Good Morning: Pavan

Nested Functions:
We can declare a function inside another function, such type of functions are called Nested
functions.

Eg:

1) def outer():
2) print("outer function started")
3) def inner():
4) print("inner function execution")
5) print("outer function calling inner function")
6) inner()
7) outer()
8) #inner() ==>NameError: name 'inner' is not defined

Output
outer function started
outer function calling inner function
inner function execution

In the above example inner() function is local to outer() function and hence it is not possible to call
directly from outside of outer() function.

Note: A function can return another function.

Eg:

1) def outer():
2) print("outer function started")
3) def inner():
4) print("inner function execution")
5) print("outer function returning inner function")
6) return inner
7) f1=outer()
8) f1()
9) f1()
10) f1()

Output
outer function started
outer function returning inner function
inner function execution
inner function execution
inner function execution

Q. What is the differenece between the following lines?


f1 = outer
f1 = outer()

 In the first case for the outer() function we are providing another name f1(function aliasing).
 But in the second case we calling outer() function,which returns inner function.For that
inner function() we are providing another name f1

Note: We can pass function as argument to another function

Eg: filter(function,sequence)
map(function,sequence)
reduce(function,sequence)
Function Decorators:
Decorator is a function which can take a function as argument and extend its functionality
and returns modified function with extended functionality.

Input Function Decorator new(add some functionality)


wish()
inner()

Input Function Decorator Output Function with


Function extended Functionality

The main objective of decorator functions is we can extend the functionality of existing
functions without modifies that function.

1) def wish(name):
2) print("Hello",name,"Good Morning")

This function can always print same output for any name

Hello Digit Good Morning


Hello Ravi Good Morning
Hello Sunny Good Morning

But we want to modify this function to provide different message if name is Sunny.
We can do this without touching wish() function by using decorator.

Eg:

1) def decor(func):
2) def inner(name):
3) if name=="Sunny":
4) print("Hello Sunny Bad Morning")
5) else:
6) func(name)
7) return inner
8)
9) @decor
10) def wish(name):
11) print("Hello",name,"Good Morning")
12)
13) wish("Digit")
14) wish("Ravi")
15) wish("Sunny")
16)
17) Output
18) Hello Digit Good Morning
19) Hello Ravi Good Morning
20) Hello Sunny Bad Morning

In the above program whenever we call wish() function automatically decor function will
be executed.

How to call same function with decorator and without decorator:

We should not use @decor

1) def decor(func):
2)def inner(name):
3) if name=="Sunny":
4) print("Hello Sunny Bad Morning")
5) else:
6) func(name)
7)return inner
8)
9)
10) def wish(name):
11)print("Hello",name,"Good Morning")
12)
13) decorfunction=decor(wish)
14)

16)
15) wish("Sunny") #decoratorwont
wish("Digit") #decorator wontbe
beexecuted
executed17)
19) decorfunction("Sunny")#decorator will be executed
18) decorfunction("Digit")#decorator will be executed
21) Output
20)
23) Hello Sunny Good Morning
22) Hello Digit Good Morning
25) Hello Sunny Bad Morning
24) Hello Digit Good Morning

Eg 2:

1) def smart_division(func):
2) def inner(a,b):
3) print("We are dividing",a,"with",b)
4) if b==0:
5) print("OOPS...cannot divide")
6) return
7) else:
8) return func(a,b)
9) return inner
10)
11) @smart_division
12) def division(a,b):
13) return a/b
14)
15) print(division(20,2))
16) print(division(20,0))
17)
18) without decorator we will get Error.In this case output is:
19)
20) 10.0
21) Traceback (most recent call last):
22) File "test.py", line 16, in <module>
23) print(division(20,0))
24) File "test.py", line 13, in division
25) return a/b
26) ZeroDivisionError: division by zero

with decorator we won't get any error. In this case output is:

We are dividing 20 with 2


10.0
We are dividing 20 with 0
OOPS...cannot divide
None

Decorator Chaining
We can define multiple decorators for the same function and all these decorators will
form Decorator Chaining.

Eg:
@decor1
@decor
def num():

For num() function we are applying 2 decorator functions. First inner decorator will work
and then outer decorator.

Eg:

1) def decor1(func):
2) def inner():
3) x=func()
4) return x*x

nd
DIGITSOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
23
5) return inner
6)
7) def decor(func):
8) def inner():
9) x=func()
10) return 2*x
11) return inner
12)
13) @decor1
14) @decor
15) def num():
16) return 10
17)
18) print(num())

Demo Program for decorator Chaining:


1) def decor(func):
2) def inner(name):
3) print("First Decor(decor) Function Execution")
4) func(name)
5) return inner
6)
7) def decor1(func):
8) def inner(name):
9) print("Second Decor(decor1) Execution")
10) func(name)
11) return inner
12)
13) @decor1
14) @decor
15) def wish(name):
16) print("Hello",name,"Good Morning")
17)
18) wish("Digit")

D:\Digitclasses>py decaratordemo1.py
Second Decor(decor1) Execution
First Decor(decor) Function Execution
Hello Digit Good Morning
Generators
Generator is a function which is responsible to generate a sequence of values.
We can write generator functions just like ordinary functions, but it uses yield keyword to
return values.

Generator
A Sequence of Values
Function

yield

Eg 1:

1) def mygen():
2) yield 'A'
3) yield 'B'
4) yield 'C'
5)
6) g=mygen()
7) print(type(g))
8)
9) print(next(g))
10) print(next(g))
11) print(next(g))
12) print(next(g))
13)
14) Output
15) <class 'generator'>
16) A
17) B
18) C
19) Traceback (most recent call last):
20) File "test.py", line 12, in <module>
21) print(next(g))
22) StopIteration

Eg 2:

1) def countdown(num):
2) print("Start Countdown")
3) while(num>0):
4) yield num
5) num=num-1
6)
7) values=countdown(5)
8) for x in values:
9) print(x)
10)
11) Output
12) Start Countdown
13) 5
14) 4
15) 3
16) 2
17) 1

Eg 3: To generate first n numbers:

1) def firstn(num):
2) n=1
3) while n<=num:
4) yield n
5) n=n+1
6)
7) values=firstn(5)
8) for x in values:
9) print(x)
10)
11) Output
12) 1
13) 2
14) 3
15) 4
16) 5

We can convert generator into list as follows:


values=firstn(10)
l1=list(values)
print(l1) #[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
Eg 4: To generate Fibonacci Numbers...

The next is the sum of previous 2 numbers

Eg: 0,1,1,2,3,5,8,13,21,...

1) def fib():
2)a,b=0,1
3)while True:
4) yield a
5) a,b=b,a+b
6) for f in fib():
7)if f>100:
8) break
9)print(f)
10)
11) Output
12) 0
13) 1
14) 1
15) 2
16) 3
17) 5
18) 8
19) 13
20) 21
21) 34
22) 55
23) 89

Advantages of Generator Functions:


1. when compared with class level iterators, generators are very easy to use
2. Improves memory utilization and performance.
3. Generators are best suitable for reading data from large number of large files
4. Generators work great for web scraping and crawling.

Generators vs Normal Collections wrt performance:


1) import random
2) import time
3)
4) names = ['Sunny','Bunny','Chinny','Vinny']
5) subjects = ['Python','Java','Blockchain']
6)
7) def people_list(num_people):
8)results = []
9)for i in range(num_people):
10) person = {
11) 'id':i,
12) 'name': random.choice(names),
13) 'subject':random.choice(subjects)
14) }
15) results.append(person)
16)return results
17)
18) def people_generator(num_people):
19)for i in range(num_people):
20) person = {
21) 'id':i,
22) 'name': random.choice(names),
23) 'major':random.choice(subjects)
24) }
25) yield person
26)
27) '''''t1 = time.clock()
28) people = people_list(10000000)
29) t2 = time.clock()'''
30)
31) t1 = time.clock()
32) people = people_generator(10000000)
33) t2 = time.clock()
34)
35) print('Took {}'.format(t2-t1))

Note: In the above program observe the differnce wrt execution time by using list and generators

Generators vs Normal Collections wrt Memory Utilization:


Normal Collection:
l=[x*x for x in range(10000000000000000)]
print(l[0])

We will get MemoryError in this case because all these values are required to store in the memory.

Generators:
g=(x*x for x in range(10000000000000000))
print(next(g))

Output: 0
We won't get any MemoryError because the values won't be stored at the beginning
Modules
A group of functions, variables and classes saved to a file, which is nothing but module.

Every Python file (.py) acts as a module.

Eg: Digitmath.py

1)x=888
2)
3) def add(a,b):
4)print("The Sum:",a+b)
5)
6) def product(a,b):
7)print("The Product:",a*b)

Digitmath module contains one variable and 2 functions.

If we want to use members of module in our program then we should import that module.

import modulename

We can access members by using module name.


modulename.variable
modulename.function()

test.py:

1) import Digitmath
2) print(Digitmath.x)
3) Digitmath.add(10,20)
4) Digitmath.product(10,20)
5)
6) Output
7) 888
8) The Sum: 30
9) The Product: 200
Note:
whenever we are using a module in our program, for that module compiled file will be
generated and stored in the hard disk permanently.

Renaming a module at the time of import (module aliasing):


Eg:
import Digitmath as m

here Digitmath is original module name and m is alias name.


We can access members by using alias name m

test.py:

1) import Digitmath as m
2) print(m.x)
3) m.add(10,20)
4) m.product(10,20)

from ... import:

We can import particular members of module by using from ... import .


The main advantage of this is we can access members directly without using module
name.

Eg:
from Digitmath import x,add
print(x)
add(10,20)
product(10,20)==> NameError: name 'product' is not defined

We can import all members of a module as follows


from Digitmath import *

test.py:

1) from Digitmath import *


2) print(x)
3) add(10,20)
4) product(10,20)
Various possibilties of import:
import modulename
import module1,module2,module3
import module1 as m
import module1 as m1,module2 as m2,module3
from module import member
from module import member1,member2,memebr3
from module import memeber1 as x
from module import *

member aliasing:
from Digitmath import x as y,add as sum
print(y)
sum(10,20)

Once we defined as alias name,we should use alias name only and we should not use
original name

Eg:
from Digitmath import x as y
print(x)==>NameError: name 'x' is not defined

Reloading a Module:
By default module will be loaded only once eventhough we are importing multiple
multiple times.

Demo Program for module reloading:


1) import time
2) from imp import reload
3) import module1
4) time.sleep(30)
5) reload(module1)
6) time.sleep(30)
7) reload(module1)
8) print("This is test file")

Note: In the above program, everytime updated version of module1 will be available to
our program
module1.py:

print("This is from module1")

test.py

1) import module1
2) import module1
3) import module1
4) import module1
5) print("This is test module")
6)
7) Output
8) This is from module1
9) This is test module

In the above program test module will be loaded only once eventhough we are importing
multiple times.

The problem in this approach is after loading a module if it is updated outside then
updated version of module1 is not available to our program.

We can solve this problem by reloading module explicitly based on our requirement.
We can reload by using reload() function of imp module.

import imp
imp.reload(module1)

test.py:

1) import module1
2) import module1
3) from imp import reload
4) reload(module1)
5) reload(module1)
6) reload(module1)
7) print("This is test module")

In the above program module1 will be loaded 4 times in that 1 time by default and 3 times
explicitly. In this case output is

1) This is from module1


2) This is from module1
3) This is from module1
4) This is from module1
5) This is test module
The main advantage of explicit module reloading is we can ensure that updated version is
always available to our program.

Finding members of module by using dir() function:

Python provides inbuilt function dir() to list out all members of current module or a
specified module.

dir() ===>To list out all members of current module


dir(moduleName)==>To list out all members of specified module

Eg 1: test.py

1) x=10
2) y=20
3) def f1():
4) print("Hello")
5) print(dir()) # To print all members of current module
6)
7) Output
8) [' annotations ', ' builtins ', ' cached ', ' doc ', ' file ', ' loader ', ' nam
e ', ' package ', ' spec ', 'f1', 'x', 'y']

Eg 2: To display members of particular module:

Digitmath.py:

1) x=888
2)
3) def add(a,b):
4)print("The Sum:",a+b)
5)
6) def product(a,b):
7)print("The Product:",a*b)

test.py:

1) import Digitmath
2) print(dir(Digitmath))
3)
4) Output
5) [' builtins ', ' cached ', ' doc ', ' file ', ' loader ', ' name ',
6) ' package ', ' spec ', 'add', 'product', 'x']

Note: For every module at the time of execution Python interpreter will add some special
properties automatically for internal use.
Eg: builtins , cached ,' doc , file , loader , name , package ,
spec

Based on our requirement we can access these properties also in our program.

Eg: test.py:

1) print( builtins )
2) print( cached )
3) print( doc )
4) print( file )
5) print( loader )
6) print( name )
7) print( package )
8) print( spec )
9)
10) Output
11) <module 'builtins' (built-in)>
12) None
13) None

test.py

1) <_frozen_importlib_external.SourceFileLoader object at 0x00572170>


2) main
3) None
4) None

The Special variable name :


For every Python program , a special variable name will be added internally.
This variable stores information regarding whether the program is executed as
an individual program or as a module.

If the program executed as an individual program then the value of this variable is
main
If the program executed as a module from some other program then the value of this
variable is the name of module where it is defined.

Hence by using this name variable we can identify whether the program executed
directly or as a module.
Demo program:
module1.py:

1) def f1():
2) if name ==' main ':
3) print("The code executed as a program")
4) else:
5) print("The code executed as a module from some other program")
6) f1()

test.py:

1)
2) import module1 3)
module1.f1()
5) The code executed as a program
4) D:\Python_classes>py module1.py
7) D:\Python_classes>py test.py
6)
9) The code executed as a module from some other program
8) The code executed as a module from some other program

Working with math module:


Python provides inbuilt module math.
This module defines several functions which can be used for mathematical operations.
The main important functions are

1. sqrt(x)
2. ceil(x)
3. floor(x)
4. fabs(x)
5.log(x)
6. sin(x)
7. tan(x)
....

Eg:

1) from math import *


2) print(sqrt(4))
3) print(ceil(10.1))
4) print(floor(10.1))
5) print(fabs(-10.6))
6) print(fabs(10.6))
7)
8) Output
9) 2.0
10) 11
11) 10
12) 10.6
13) 10.6

Note:
We can find help for any module by using help() function

Eg:

import math
help(math)

Working with random module:


This module defines several functions to generate random numbers.
We can use these functions while developing games,in cryptography and to generate
random numbers on fly for authentication.

1. random() function:

This function always generate some float value between 0 and 1 ( not inclusive)
0<x<1

Eg:

1) from random import *


2) for i in range(10):
3) print(random())
4)
5)Output
6)0.4572685609302056
7) 0.6584325233197768
8) 0.15444034016553587
9) 0.18351427005232201
10) 0.1330257265904884
11) 0.9291139798071045
12) 0.6586741197891783
13) 0.8901649834019002
14) 0.25540891083913053
15) 0.7290504335962871
2. randint() function:

To generate random integer beween two given numbers(inclusive)

Eg:

1) from random import *


2) for i in range(10):
3) print(randint(1,100)) # generate random int value between 1 and 100(inclusive)
4)
5) Output
6) 51
7) 44
8) 39
9) 70
10) 49
11) 74
12) 52
13) 10
14) 40
15) 8

3. uniform():

It returns random float values between 2 given numbers(not inclusive)

Eg:

1) from random import *


2) for i in range(10):
3) print(uniform(1,10))
4)
5) Output
6) 9.787695398230332
7) 6.81102218793548
8) 8.068672144377329
9) 8.567976357239834
10) 6.363511674803802
11) 2.176137584071641
12) 4.822867939432386
13) 6.0801725149678445
14) 7.508457735544763
15) 1.9982221862917555

random() ===>in between 0 and 1 (not inclusive)


randint(x,y) ==>in between x and y ( inclusive)
uniform(x,y) ==> in between x and y ( not inclusive)
4. randrange([start],stop,[step])

returns a random number from range


start<= x < stop
start argument is optional and default value is 0
step argument is optional and default value is 1

randrange(10)-->generates a number from 0 to 9


randrange(1,11)-->generates a number from 1 to 10
randrange(1,11,2)-->generates a number from 1,3,5,7,9

Eg 1:

1) from random import *


2) for i in range(10):
3) print(randrange(10))
4)
5) Output
6) 9
7) 4
8) 0
9) 2
10) 9
11) 4
12) 8
13) 9
14) 5
15) 9

Eg 2:

1) from random import *


2) for i in range(10):
3) print(randrange(1,11))
4)
5) Output
6) 2
7) 2
8) 8
9) 10
10) 3
11) 5
12) 9
13) 1
14) 6
15) 3
Eg 3:

1) from random import *


2) for i in range(10):
3) print(randrange(1,11,2))
4)
5) Output
6) 1
7) 3
8) 9
9) 5
10) 7
11) 1
12) 1
13) 1
14) 7
15) 3

5. choice() function:

It wont return random number.


It will return a random object from the given list or tuple.

Eg:

1) from random import *


2) list=["Sunny","Bunny","Chinny","Vinny","pinny"]
3) for i in range(10):
4) print(choice(list))

Output
Bunny
pinny
Bunny
Sunny
Bunny
pinny
pinny
Vinny
Bunny
Sunny
Packages
It is an encapsulation mechanism to group related modules into a single unit.
package is nothing but folder or directory which represents collection of Python modules.

Any folder or directory contains init .py file,is considered as a Python package.This file
can be empty.

A package can contains sub packages also.

init .py
File 1

File 1 File 1

init .py init .py


m.py n.py
x.py y.py

Home Loan Vehicle Loan

Loan
init .py
File 1

File 1 File 1

init .py init .py


Module 1 Module 1 Module 1 Module 1

Home Loan Vehicle Loan

Loan

The main advantages of package statement are

1. We can resolve naming conflicts


2. We can identify our components uniquely
3. It improves modularity of the

application Eg 1:

D:\Python_classes>
|-test.py
|-pack1
|-module1.py
|- init .py

init .py:

empty file

module1.py:
def f1():
print("Hello this is from module1 present in pack1")

test.py (version-1):
import pack1.module1
pack1.module1.f1()
test.py (version-2):

from pack1.module1 import f1


f1()

Eg 2:

D:\Python_classes>
|-test.py
|-com
|-module1.py
|- init .py
|-Digitsoft
|-module2.py
|- init .py

init .py:

empty file

module1.py:

def f1():
print("Hello this is from module1 present in com")

module2.py:

def f2():
print("Hello this is from module2 present in com.Digitsoft")

test.py:

1. from com.module1 import f1


2. from com.Digitsoft.module2 import f2
3. f1()
4. f2()
5.
6. Output
7. D:\Python_classes>py test.py
8. Hello this is from module1 present in com
9. Hello this is from module2 present in com.Digitsoft

Note: Summary diagram of library,packages,modules which contains functions,classes


and variables.
Library

pack 1 pack 2 --------------- pack n

module 1 module 2 module n module 1 module 2 module n

function 1 function 2 function n variables classes


File Handling
As the part of programming requirement, we have to store our data permanently for
future purpose. For this requirement we should go for files.

Files are very common permanent storage areas to store our data.

Types of Files:
There are 2 types of files

1. Text Files:

Usually we can use text files to store character data


eg: abc.txt

2. Binary Files:

Usually we can use binary files to store binary data like images,video files, audio files etc...

Opening a File:
Before performing any operation (like read or write) on the file,first we have to open that
file.For this we should use Python's inbuilt function open()

But at the time of open, we have to specify mode,which represents the purpose of
opening file.

f = open(filename, mode)

The allowed modes in Python are

1. r  open an existing file for read operation. The file pointer is positioned at
the beginning of the file.If the specified file does not exist then we will get
FileNotFoundError.This is default mode.
2. w  open an existing file for write operation. If the file already contains some data
then it will be overridden. If the specified file is not already avaialble then this mode
will create that file.

3. a  open an existing file for append operation. It won't override existing data.If
the specified file is not already avaialble then this mode will create a new file.

4. r+  To read and write data into the file. The previous data in the file will not be
deleted.The file pointer is placed at the beginning of the file.

5. w+  To write and read data. It will override existing data.

6. a+  To append and read data from the file.It wont override existing data.

7. x  To open a file in exclusive creation mode for write operation. If the file already
exists then we will get FileExistsError.

Note: All the above modes are applicable for text files. If the above modes suffixed with
'b' then these represents for binary files.

Eg: rb,wb,ab,r+b,w+b,a+b,xb

f = open("abc.txt","w")

We are opening abc.txt file for writing data.

Closing a File:
After completing our operations on the file,it is highly recommended to close the file.
For this we have to use close() function.

f.close()

Various properties of File Object:


Once we opend a file and we got file object,we can get various details related to that file
by using its properties.

name  Name of opened file


mode  Mode in which the file is opened
closed  Returns boolean value indicates that file is closed or not
readable() Retruns boolean value indicates that whether file is readable or not
writable() Returns boolean value indicates that whether file is writable or not.
Eg:

1) f=open("abc.txt",'w')
2) print("File Name: ",f.name)
3) print("File Mode: ",f.mode)
4) print("Is File Readable: ",f.readable())
5) print("Is File Writable: ",f.writable())
6) print("Is File Closed : ",f.closed)
7) f.close()
8) print("Is File Closed : ",f.closed)
9)
10)
11) Output
12) D:\Python_classes>py test.py
13) File Name: abc.txt
14) File Mode: w
15) Is File Readable: False
16) Is File Writable: True
17) Is File Closed : False
18) Is File Closed : True

Writing data to text files:


We can write character data to the text files by using the following 2 methods.

write(str)
writelines(list of lines)

Eg:

1) f=open("abcd.txt",'w')
2) f.write("Digit\n")
3) f.write("Software\n")
4) f.write("Solutions\n")
5) print("Data written to the file successfully")
6) f.close()

abcd.txt:
Digit
Software
Solutions

Note: In the above program, data present in the file will be overridden everytime if we
run the program. Instead of overriding if we want append operation then we should open
the file as follows.

f = open("abcd.txt","a")
Eg 2:

1) f=open("abcd.txt",'w')
2) list=["sunny\n","bunny\n","vinny\n","chinny"]
3) f.writelines(list)
4) print("List of lines written to the file successfully")
5) f.close()

abcd.txt:
sunny
bunny
vinny
chinny

Note: while writing data by using write() methods, compulsory we have to provide line
seperator(\n),otherwise total data should be written to a single line.

Reading Character Data from text files:


We can read character data from text file by using the following read methods.

read() To read total data from the file


read(n)  To read 'n' characters from the file
readline() To read only one line
readlines() To read all lines into a list

Eg 1: To read total data from the file

1) f=open("abc.txt",'r')
2) data=f.read()
3) print(data)
4) f.close()
5)
6) Output
7) sunny
8) bunny
9) chinny
10) vinny

Eg 2: To read only first 10 characters:

1) f=open("abc.txt",'r')
2) data=f.read(10)
3) print(data)
4) f.close()
5)
6) Output
7) sunny
8) bunn

Eg 3: To read data line by line:

1) f=open("abc.txt",'r')
2) line1=f.readline()
3) print(line1,end='')
4) line2=f.readline()
5) print(line2,end='')
6) line3=f.readline()
7) print(line3,end='')
8) f.close()
9)
10) Output
11) sunny
12) bunny
13) chinny

Eg 4: To read all lines into list:

1) f=open("abc.txt",'r')
2) lines=f.readlines()
3) for line in lines:
4)print(line,end='')
5) f.close()
6)
7) Output
8) sunny
9) bunny
10) chinny
11) vinny

Eg 5:

1) f=open("abc.txt","r")
2) print(f.read(3))
3) print(f.readline())
4) print(f.read(4))
5) print("Remaining data")
6) print(f.read())
7)
8) Output
9) sun
10) ny
11)
12) bunn
13) Remaining data
14) y
15) chinny
16) vinny

The with statement:


The with statement can be used while opening a file.We can use this to group file
operation statements within a block.
The advantage of with statement is it will take care closing of file,after completing all
operations automatically even in the case of exceptions also, and we are not required to
close explicitly.
Eg:

1) with open("abc.txt","w") as f:
2) f.write("Digit\n")
3) f.write("Software\n")
4) f.write("Solutions\n")
5) print("Is File Closed: ",f.closed)
6) print("Is File Closed: ",f.closed)
7)
8) Output
9) Is File Closed: False
10) Is File Closed: True

The seek() and tell() methods:

tell():

==>We can use tell() method to return current position of the cursor(file pointer) from
beginning of the file. [ can you plese telll current cursor position]
The position(index) of first character in files is zero just like string index.

Eg:

1) f=open("abc.txt","r")
2) print(f.tell())
3) print(f.read(2))
4) print(f.tell())
5) print(f.read(3))
6) print(f.tell())

abc.txt:
sunny
bunny
chinny
vinny
Output:
0
su
2
nny
5

seek():

We can use seek() method to move cursor(file pointer) to specified location.


[Can you please seek the cursor to a particular location]

f.seek(offset, fromwhere)

offset represents the number of positions

The allowed values for second attribute(from where) are


0- - ->From beginning of file(default value)
1>From current position
2>From end of the file

Note: Python 2 supports all 3 values but Python 3 supports only zero.
Eg:

1) data="All Students are STUPIDS"


2) f=open("abc.txt","w")
3) f.write(data)
4) with open("abc.txt","r+") as f:
5) text=f.read()
6) print(text)
7) print("The Current Cursor Position: ",f.tell())
8) f.seek(17)
9) print("The Current Cursor Position: ",f.tell())
10) f.write("GEMS!!!")
11) f.seek(0)
12) text=f.read()
13) print("Data After Modification:")
14) print(text)
15)
16) Output
17)
18) All Students are STUPIDS
19) The Current Cursor Position: 24
20) The Current Cursor Position: 17
21) Data After Modification:
22) All Students are GEMS!!!

How to check a particular file exists or not?

We can use os library to get information about files in our computer.


os module has path sub module,which contains isFile() function to check whether a
particular file exists or not?
os.path.isfile(fname)

Q. Write a program to check whether the given file exists or not. If it is


available then print its content?

1) import os,sys
2) fname=input("Enter File Name: ")
3) if os.path.isfile(fname):
4) print("File exists:",fname)
5) f=open(fname,"r")
6) else:
7) print("File does not exist:",fname)
8) sys.exit(0)
9) print("The content of file is:")
10) data=f.read()
11) print(data)
12)
13) Output
14) D:\Python_classes>py test.py
15) Enter File Name: Digit.txt
16) File does not exist: Digit.txt
17)
18) D:\Python_classes>py test.py
19) Enter File Name: abc.txt
20) File exists: abc.txt
21) The content of file is:
22) All Students are GEMS!!!
23) All Students are GEMS!!!
24) All Students are GEMS!!!
25) All Students are GEMS!!!
26) All Students are GEMS!!!
27) All Students are GEMS!!!

Note:
sys.exit(0) ===>To exit system without executing rest of the program.
argument represents status code . 0 means normal termination and it is the default value.
Q. Program to print the number of lines,words and characters present in the
given file?

1) import os,sys
2) fname=input("Enter File Name: ")
3) if os.path.isfile(fname):
4) print("File exists:",fname)
5) f=open(fname,"r")
6) else:
7) print("File does not exist:",fname)
8) sys.exit(0)
9) lcount=wcount=ccount=0
10) for line in f:
11) lcount=lcount+1
12) ccount=ccount+len(line)
13) words=line.split()
14) wcount=wcount+len(words)
15) print("The number of Lines:",lcount)
16) print("The number of Words:",wcount)
17) print("The number of Characters:",ccount)
18)
19) Output
20) D:\Python_classes>py test.py
21) Enter File Name: Digit.txt
22) File does not exist: Digit.txt
23)
24) D:\Python_classes>py test.py
25) Enter File Name: abc.txt
26) File exists: abc.txt
27) The number of Lines: 6
28) The number of Words: 24
29) The number of Characters: 149

abc.txt:

All Students are GEMS!!!


All Students are GEMS!!!
All Students are GEMS!!!
All Students are GEMS!!!
All Students are GEMS!!!
All Students are GEMS!!!
Handling Binary Data:
It is very common requirement to read or write binary data like images,video files,audio
files etc.

Q. Program to read image file and write to a new image file?

1) f1=open("rossum.jpg","rb")
2) f2=open("newpic.jpg","wb")
3) bytes=f1.read()
4) f2.write(bytes)
5) print("New Image is available with the name: newpic.jpg")

Handling csv files:


CSV==>Comma seperated values

As the part of programming,it is very common requirement to write and read data wrt csv
files. Python provides csv module to handle csv files.

Writing data to csv file:


1) import csv
2) with open("emp.csv","w",newline='') as f:
3) w=csv.writer(f) # returns csv writer object
4) w.writerow(["ENO","ENAME","ESAL","EADDR"])
5) n=int(input("Enter Number of Employees:"))
6) for i in range(n):
7) eno=input("Enter Employee No:")
8) ename=input("Enter Employee Name:")
9) esal=input("Enter Employee Salary:")
10) eaddr=input("Enter Employee Address:")
11) w.writerow([eno,ename,esal,eaddr])
12) print("Total Employees data written to csv file successfully")

Note: Observe the difference with newline attribute and without

with open("emp.csv","w",newline='') as f:
with open("emp.csv","w") as f:

Note: If we are not using newline attribute then in the csv file blank lines will be included
between data. To prevent these blank lines, newline attribute is required in Python-3,but
in Python-2 just we can specify mode as 'wb' and we are not required to use newline
attribute.
Reading Data from csv file:
1) import csv
2) f=open("emp.csv",'r')
3) r=csv.reader(f) #returns csv reader object
4) data=list(r)
5) #print(data)
6) for line in data:
7) for word in line:
8) print(word,"\t",end='')
9) print()
10)
11) Output
12) D:\Python_classes>py test.py
13) ENO ENAME ESAL EADDR
14) 100 Digit 1000 Hyd
15) 200 Sachin 2000 Mumbai
16) 300 Dhoni 3000 Ranchi

Zipping and Unzipping Files:

It is very common requirement to zip and unzip files.


The main advantages are:

1. To improve memory utilization


2. We can reduce transport time
3. We can improve performance.

To perform zip and unzip operations, Python contains one in-bulit module zip file.
This module contains a class : ZipFile

To create Zip file:

We have to create ZipFile class object with name of the zip file,mode and constant
ZIP_DEFLATED. This constant represents we are creating zip file.

f = ZipFile("files.zip","w","ZIP_DEFLATED")

Once we create ZipFile object,we can add files by using write() method.

f.write(filename)
Eg:

1) from zipfile import *


2) f=ZipFile("files.zip",'w',ZIP_DEFLATED)
3) f.write("file1.txt")
4) f.write("file2.txt")
5) f.write("file3.txt")
6) f.close()
7) print("files.zip file created successfully")

To perform unzip operation:

We have to create ZipFile object as follows

f = ZipFile("files.zip","r",ZIP_STORED)

ZIP_STORED represents unzip operation. This is default value and hence we are not
required to specify.
Once we created ZipFile object for unzip operation,we can get all file names present in
that zip file by using namelist() method.

names = f.namelist()

Eg:

1) from zipfile import *


2) f=ZipFile("files.zip",'r',ZIP_STORED)
3) names=f.namelist()
4) for name in names:
5) print( "File Name: ",name)
6) print("The Content of this file is:")
7) f1=open(name,'r')
8) print(f1.read())
9) print()

Working with Directories:

It is very common requirement to perform operations for directories like

1. To know current working directory


2. To create a new directory
3. To remove an existing directory
4. To rename a directory
5. To list contents of the
directory etc...
To perform these operations,Python provides inbuilt module os,which contains several
functions to perform directory related operations.

Q1. To Know Current Working Directory:

import os
cwd=os.getcwd()
print("Current Working Directory:",cwd)

Q2. To create a sub directory in the current working directory:

import os
os.mkdir("mysub")
print("mysub directory created in cwd")

Q3. To create a sub directory in mysub directory:

cwd
|-mysub
|-mysub2

import os
os.mkdir("mysub/mysub2")
print("mysub2 created inside mysub")

Note: Assume mysub already present in cwd.

Q4. To create multiple directories like sub1 in that sub2 in that sub3:

import os
os.makedirs("sub1/sub2/sub3")
print("sub1 and in that sub2 and in that sub3 directories created")

Q5. To remove a directory:

import os
os.rmdir("mysub/mysub2")
print("mysub2 directory deleted")

Q6. To remove multiple directories in the path:

import os
os.removedirs("sub1/sub2/sub3")
print("All 3 directories sub1,sub2 and sub3 removed")
Q7. To rename a directory:

import os
os.rename("mysub","newdir")
print("mysub directory renamed to newdir")

Q8. To know contents of directory:

os module provides listdir() to list out the contents of the specified directory. It won't
display the contents of sub directory.

Eg:

1) import os
2) print(os.listdir("."))
3)
4) Output
5) D:\Python_classes>py test.py
6) ['abc.py', 'abc.txt', 'abcd.txt', 'com', 'demo.py', 'Digitmath.py', 'emp.csv', '
7) file1.txt', 'file2.txt', 'file3.txt', 'files.zip', 'log.txt', 'module1.py', 'myl
8) og.txt', 'newdir', 'newpic.jpg', 'pack1', 'rossum.jpg', 'test.py', ' pycache '
9) ]

The above program display contents of current working directory but not contents of sub
directories.

If we want the contents of a directory including sub directories then we should go for
walk() function.

Q9. To know contents of directory including sub directories:

We have to use walk() function


[Can you please walk in the directory so that we can aware all contents of that directory]

os.walk(path,topdown=True,onerror=None,followlinks=False)

It returns an Iterator object whose contents can be displayed by using for loop

path-->Directory path. cwd means .


topdown=True --->Travel from top to bottom
onerror=None --->on error detected which function has to execute.
followlinks=True -->To visit directories pointed by symbolic links
Eg: To display all contents of Current working directory including sub directories:
1) import os
2) for dirpath,dirnames,filenames in os.walk('.'):
3) print("Current Directory Path:",dirpath)
4) print("Directories:",dirnames)
5) print("Files:",filenames)
6) print()
7)
8)
9) Output
10) Current Directory Path: .
11) Directories: ['com', 'newdir', 'pack1', ' pycache ']
12) Files: ['abc.txt', 'abcd.txt', 'demo.py', 'Digitmath.py', 'emp.csv', 'file1.txt'
13) , 'file2.txt', 'file3.txt', 'files.zip', 'log.txt', 'module1.py', 'mylog.txt', '
14) newpic.jpg', 'rossum.jpg', 'test.py']
15)
16) Current Directory Path: .\com
17) Directories: ['Digitsoft', ' pycache ']
18) Files: ['module1.py', ' init .py']
19)
20) ...

Note: To display contents of particular directory,we have to provide that directory name
as argument to walk() function.

os.walk("directoryname")

Q. What is the difference between listdir() and walk() functions?

In the case of listdir(), we will get contents of specified directory but not sub directory
contents. But in the case of walk() function we will get contents of specified directory and
its sub directories also.

Running Other programs from Python program:

os module contains system() function to run programs and commands.


It is exactly same as system() function in C language.

os.system("commad string")
The argument is any command which is executing from DOS.

Eg:
import os
os.system("dir *.py")
os.system("py abc.py")
How to get information about a File:

We can get statistics of a file like size, last accessed time,last modified time etc by using
stat() function of os module.

stats = os.stat("abc.txt")

The statistics of a file includes the following parameters:

st_mode==>Protection Bits
st_ino==>Inode number
st_dev===>device
st_nlink===>no of hard links
st_uid===>userid of owner
st_gid==>group id of owner
st_size===>size of file in bytes
st_atime==>Time of most recent access
st_mtime==>Time of Most recent modification
st_ctime==> Time of Most recent meta data change

Note:

st_atime, st_mtime and st_ctime returns the time as number of milli seconds since Jan 1st
1970 ,12:00AM. By using datetime module fromtimestamp() function,we can get exact
date and time.

Q. To print all statistics of file abc.txt:

1) import os
2) stats=os.stat("abc.txt")
3) print(stats)
4)
5) Output
6) os.stat_result(st_mode=33206, st_ino=844424930132788, st_dev=2657980798, st_nlin
7) k=1, st_uid=0, st_gid=0, st_size=22410, st_atime=1505451446, st_mtime=1505538999
8) , st_ctime=1505451446)

Q. To print specified properties:

1) import os
2) from datetime import *
3) stats=os.stat("abc.txt")
4) print("File Size in Bytes:",stats.st_size)
5) print("File Last Accessed Time:",datetime.fromtimestamp(stats.st_atime))
6) print("File Last Modified Time:",datetime.fromtimestamp(stats.st_mtime))
7)

You might also like