0% found this document useful (0 votes)
57 views52 pages

PP Unit II Data Types Notes For Mc4103

Uploaded by

saishan3003
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
57 views52 pages

PP Unit II Data Types Notes For Mc4103

Uploaded by

saishan3003
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 52

lOMoARcPSD|24825242

PP UNIT-II - Lecture notes for MC4103

Python programming (Anna University)

Scan to open on Studocu

Studocu is not sponsored or endorsed by any college or university


Downloaded by sai shan3003 ([email protected])
lOMoARcPSD|24825242

UNIT II

DATA TYPES IN PYTHON


STRINGS
String is defined as sequence of characters represented in quotation marks (either
single quotes ( ‘ ) or double quotes ( “ ). An individual character in a string is accessed using an
index. Index ranges from 0 to n-1. Strings are immutable i.e. the contents of the string cannot
be changed after it is created.
Operations on String:
i) Indexing
ii) Slicing
iii) Concatenation
iv) Repetition
v) Membership
vi) Comparison

i) Indexing

Positive indexing helps in accessing the string from the beginning. Negative subscript helps
in accessing the string from the end.

>>>a=”HELLO HAI”
>>>print(a[0])
>>>H
>>>print(a[-1])
>>>I
ii) Slicing
The slice[start : stop] operator extracts sub string from the strings. A segment of a string
is called a slice.

Downloaded by sai shan3003 ([email protected])


lOMoARcPSD|24825242

print[0:4] – HELL
print[ :3] – HEL
print[0: ]- HELLO
iii) Concatenation
The + operator joins the text on both sides of the operator.
a=”save”

b=”water”
>>>print(a+b)
savewater
iv) Repetition
The * operator repeats the string on the left hand side times the value on right hand side.
a=”python”

>>>print(3*a)
pythonpythonpython
v) Membership
Using membership operators to check a particular character is in string or not. Returns
true if present.

>>> s="good morning"


>>>"m" in s
True

>>> "a" not in s


True
vi) Comparison
The strings can be compared using relational operators.
>>>msg1=”Good”
>>>msg2=”Good”
>>>msg1==msg2
True

Downloaded by sai shan3003 ([email protected])


lOMoARcPSD|24825242

>>>msg1!=msg2
False

Downloaded by sai shan3003 ([email protected])


lOMoARcPSD|24825242

String slices
A part of a string is called string slices. The process of extracting a sub string from a
string is called slicing. The Slice[n : m] operator extracts substring from the strings. A segment
of a string is called a slice.
a=”HELLO”
print[0:4] – HELL
print[ :3] – HEL
print[0: ]- HELLO

Immutability
Python strings are “immutable” as they cannot be changed after they are created.
Therefore [ ] operator cannot be used on the left side of an assignment.

Operations Example Output


element assignment a="PYTHON" TypeError: 'str' object does not
a[0]='x' support element assignment
element deletion a=”PYTHON” TypeError: 'str' object doesn't
del a[0] support element deletion
delete a string a=”PYTHON” NameError: name 'my_string'
del a is not defined
print(a)

String built in functions and methods


A method is a function that “belongs to” an object.
Syntax :
To access the method
stringname.method()
Example:
a=”happy birthday”
here, a is the string name.

Downloaded by sai shan3003 ([email protected])


lOMoARcPSD|24825242

Sl.No Syntax Example Description


1. a. capitalize() >>> a. capitalize() capitalize only the first letter in
' Happy birthday’ a string
2. a. upper() >>> a. upper() change string to upper case
'HAPPY BIRTHDAY’
3. a. lower() >>> a. lower() change string to lower case
' happy birthday’
4. a.title() >>> a.title() change string to title case i.e.
' Happy Birthday ' first characters of all the words
are capitalized.

5. a.swapcase() >>>a.swapcase() change lowercase characters to


'HAPPY BIRTHDAY' uppercase and vice versa
6. a.split() >>> a.split() returns a list of words
['happy', 'birthday'] separated by space
7. a.count(substring) >>> a.count('happy') returns the number of
1 occurences of substring

8. a.replace(old,new) >>>a.replace('happy', replace all old substrings


'wishyou happy') with new substrings
'wishyou happy
birthday'
9. a.isupper() >>> a.isupper() checks whether all the case
False based characters (letters) of
the string are uppercase.
10. a.islower() >>> a.islower() checks whether all the
True casebased
characters (letters) of
the string are lowercase.

Downloaded by sai shan3003 ([email protected])


lOMoARcPSD|24825242

11. a.isalpha() >>> a.isalpha() checks whether the string


False consists of alphabetic
characters only.
12. a.isalnum() >>> a.isalnum() checks whether the string
False consists of alphanumeric
characters.
13. a.isdigit() >>> a.isdigit() checks whether the string
False consists of digits only.
14. a.isspace() >>> a.isspace() checks whether the string
False consists of whitespace only.
15. a.istitle() >>> a.istitle() checks whether string is title
False cased.
16. a.startswith >>> a.startswith("h") checks whether string starts
(substring) True with substring
17. a.endswith(substring) >>>a.endswith("y") checks whether the string ends
True with the substring
18. len(a) >>>len(a) Return the length of the string
>>>14
19. min(a) >>>min(a) Return the minimum
>>>’ ‘ character in the string
20. max(a) max(a) Return the maximum
>>>’y’ character in the string

String modules
A module is a file containing Python definitions, functions, statements.
Standard library of Python is extended as modules.
To use these modules in a program, programmer needs to import the module.
Once we import a module, we can refer or use any of its functions or variables.
There is large number of standard modules also available in python.

Downloaded by sai shan3003 ([email protected])


lOMoARcPSD|24825242

Standard modules are imported the same way as we import user-defined modules.

Downloaded by sai shan3003 ([email protected])


lOMoARcPSD|24825242

Syntax:
import module_name
Example Program:
import string
print(string.digits)
print(string.printable)

print(string.capwords("happy birthday"))
print(string.hexdigits)
print(string.octdigits)
Output:
0123456789
0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJ
Happy Birthday

0123456789abcdefABCDEF
01234567

List as array
Array:
Array is a collection of similar elements. Elements in the array can be accessed by index.
Index starts with 0. Array can be handled in Python by module named array. To create array
have to import array module in the program.
Syntax:
import array
Syntax to create array:
arrayname = modulename.functionname(‘datatype’,[elements])
Example:
a=array.array(‘i’,[1,2,3,4])
Here,

Downloaded by sai shan3003 ([email protected])


lOMoARcPSD|24825242

a- r datatype
array
name
a
r
r
a
y
-

m
o
d
u
l
e

n
a
m
e

i
-

i
n
t
e
g
e

Downloaded by sai shan3003 ([email protected])


lOMoARcPSD|24825242

Example Program: Program to find sum of array


elements import array

sum=0 a=array.array('i',
[1,2,3,4]) for i in a:
sum=sum
+i print(sum)
Output:
10
Convert list into array:
fromlist() function is used to append list to array. Here the list is act like a array.
Syntax:
arrayname.fromlist(listname)
Example Program: Program to convert list into
array import array

sum=0
l=[6,7,8,9,5
]

a=array.array('i',[])
a.fromlist(l)

for i in a:
sum=sum
+i print(sum)
Output
35
Methods in array:
a=[2,3,4,5]
Sl.No Syntax Example Description

Downloaded by sai shan3003 ([email protected])


lOMoARcPSD|24825242

1 array(data type,value list) array(‘i’,[2,3,4,5]) This function is used to create an


array with data type and value list
specified in its arguments.

2 append() >>>a.append(6) This method is used to add end of


[2,3,4,5,6] the array.
3 insert(index,element) >>>a.insert(2,10) This method is used to add the
[2,3,10,5,6] value at the position specified in
its argument.
4 pop(index) >>>a.pop(1) This function removes the
[2,10,5,6] element at the position mentioned
in its argument, and returns it.
5 index(element) >>>a.index(2) This function returns the index of
0 value
6 reverse() >>>a.reverse() This function reverses the array.
[6,5,10,2]
7 count() a.count() This is used to count number of
4 elements in an array

LISTS, TUPLES, DICTIONARIES

LIST
List contain elements of various data types, the list is enclosed by square brackets where
elements are separated by commas. The values in a list are called elements or items. A list within
another list is called nested list.
 List values can be accessed using slice operator ([] or [:])
 list[0] represents beginning of list
 list[-1] represents ending of list
Syntax:
listname=[value1,value2,…value n]
Example :

Downloaded by sai shan3003 ([email protected])


lOMoARcPSD|24825242

>>>mylist = [10,10.5, ‘programming’]


Example program for creating lists:
list1 = [‘Rama’, ‘Delhi’, 2018] # list of different types of elements
list2 = [10, 20, 30, 40, 50] # list of numbers
list3 = [] # empty list
list4 = [‘Prema’, 2018, 99.8, [‘Mumbai’, ‘India’]] # nested list
print list1
print list2, list3
print list4
Output:
[‘Rama’, ‘Delhi’, 2018]
[10, 20, 30, 40, 50] [ ]
[‘Prema’, 2018, 99.8, [‘Mumbai’, ‘India’]]
Creating list:
i) The simplest way to create a list is enclose the elements in square
brackets([]) nlist =[10,20,30,40]
slist =[“Hai”, “Python”]
ii) A list that contains no element is called an empty list. It can be created with empty brackets
[]. elist = []

iii) A list within another list is called a nested


list. nlist =[“phyton”,2.5,[50,100,10,55]]
Accessing list elements:
The indices of list’s elements are numbered from 0 from the left end and numbered from
-1 from the right end. To access the element(s) of a list, subscript operator [ ] (also known as
slicing operator) is used. Index within [ ] indicates the position of the particular element in the
list and it must be an integer expression.
Indexing:
Just like strings, we can access elements on a list with the index. The various types are
i) Negative indexing
The index of -1 refers to the last item, -2 to the second to the last item and so on.

Downloaded by sai shan3003 ([email protected])


lOMoARcPSD|24825242

Example Program:
>>>birds[“parrot”,”Dove”,”duck”,”cuckoo”]
>>>birds[-1]
cuckoo
>>> birds[-4]
parrot
ii) Nested indexing:
A list within another list is called as nested list.
Example Program:
>>>nlist = [“Python”,8.5,[5,1,3,4,5.5]]
>>>nlist[0]
Python
>>>nlist[0][3]
h
List operations
List provides a set of operations. They are
i) Concatenation
ii) Repetition
iii) Indexing
iv) Membership
i) Concatenation
The list can be concatenated by using ‘+’ operator.
Example:
>>>a = [1,2,3]
>>>b =[4,5,6]
>>>c =a+b
>>>c
[1,2,3,4,5,6]
ii) Repetition
The list can be repeated by using * operator.

Downloaded by sai shan3003 ([email protected])


lOMoARcPSD|24825242

Example:
>>>a =[1,2,3]
>>>a*2
[1,2,3, 1,2,3]
>>>[1]*5
[1,1,1,1,1]
iii) Indexing
The list elements can be accessed by using index operator ([]).
Example:
>>>a =[1,2,3]
>>>a[0]
1
>>>a[1]
2
>>>a[2]
3
>>>a[-1]
3
iv) Membership
There are 2 membership operators in python programming.
i) in - Returns true if value is in list, returns false if value is not in list.
ii) not in - Returns true if value is not in list, returns false if value is in list.
Example:
>>>a= [1,2,3]
>>>1 in a
True
>>>4 in a
False
>>>3 not in a
False

Downloaded by sai shan3003 ([email protected])


lOMoARcPSD|24825242

List slices
A segment of list is called as list slice. The list elements can be accessed using the slice
operator ([]). Slice operator [n:m] returns a part of list from nth element to mth element ,
including first and excluding last.
If the first index is omitted, the slice starts at the beginning of the string. If the second
index is omitted, the slice goes to the end of the string. If the first index is greater than or equal
to the second, the slice is an empty string. If both indices are omitted, the slice is a given string
itself.
Syntax:
listname [start: finish -1]
Example:
>>>mylist=[‘Python’,10,10.5,’program’]
>>>mylist[0]
‘Python’
>>>mylist[1]
10
>>>mylist[2]
10.5
>>>mylist[3]
‘program’
>>>mylist[0:3]
[‘Python’,10,10.5]
>>>mylist[1:3]
[10, 10.5]
>>>mylist[:3]
[‘Python’,10,10.5]
>>>mylist[:]
[‘Python’,10,10.5,’program’]
>>>mylist[1:]
[10,10.5,’program’]

Downloaded by sai shan3003 ([email protected])


lOMoARcPSD|24825242

mylist
python 10 10.5 program
0 1 2 3
mylist[0] -> element in 0th position.
mylist[-1] -> element in ending of list
mylist[0:3] -> Starting from 0th position to 2nd position
mylist[1:] -> ending position is not given , so 1st position to ending of list
mylist[:] -> beginning to ending of list.
List methods
Python provides a set of list methods. They are
i) append()
ii) extend()
iii) sort()
iv) reverse()
v) pop()
vi) clear()
vii) index()
viii) count()
ix) insert()
x) remove()
xi) copy()
i) append()
Adds element to the end of specified list and does not return any value.
>>>a =[1,2,3]
>>>a.append(4)
>>>a
[1,2,3,4]
ii) extend()
This method add all elements of list to another list.
>>>a= [1,2,3]

Downloaded by sai shan3003 ([email protected])


lOMoARcPSD|24825242

>>>b=[4,5,6]
>>>a.extend(b)
>>>a
[1,2,3,4,5,6]
iii) sort()

This method sorts elements in list.


>>>a= [3,1,2]
>>>a.sort()
>>>a
]

Downloaded by sai shan3003 ([email protected])


lOMoARcPSD|24825242

iv) reverse()
This method reverse the elements in a list.
>>>a =[1,2,3]
>>>a.reverse()
>>>a
[3,2,1]
v) pop()
This method removes and returns an element at the given index. If the index is not given,
it removes and returns the last element on the list.
Example:
list=[“eng”,”chem”,”python”,”maths”]
>>>list.pop(2)
python
>>>list.pop()
[“eng”,”chem,’python”]
vi) clear()
This method clear elements in a list.
>>>a= [1,2,3]
>>>a.clear()
>>>print(a)
[]
vii) index()
This method returns index of given element. If the element is not in the list, it returns
error.

>>>a= [1,2,3]
>>>a.index(2)
1
viii) count()

Downloaded by sai shan3003 ([email protected])


lOMoARcPSD|24825242

Syntax:
It counts how many times the elements occur in the list.
>>>a= [1,2,3,2]
>>>a.count()
2

Downloaded by sai shan3003 ([email protected])


lOMoARcPSD|24825242

listname.count(value)
ix) insert()
It inserts an element on a desired position of a list.
Syntax:
listname.insert(index,element)
>>>a=[1,2,3]
>>>a.insert(1,4)
>>>a
[1,4,2,3]
x) remove()

It removes the specified element from the list.


>>>a=[1,2,3]
>>>a.remove(2)
>>>print(a)
[1,3]
xi) copy()

It copies one list to another list.


>>>a =[1,2,3]
>>>b=a.copy()
>>>b
[1,2,3]
Syntax:
listname.copy()
List functions:
i) len()
ii) max()
iii) min()
iv) cmp()
v) sum()
vi) sorted()

Downloaded by sai shan3003 ([email protected])


lOMoARcPSD|24825242

i) len() : Returns the number of elements in a list.


>>>a= [1,2,3,4]
>>>len(a)
4
ii) max(): Returns maximum value from the list .
>>>a= [1,2,3,4]
>>>max(a)
4
iii) min(): Returns minimum value from list.
>>>a= [1,2,3,4]
>>>min(a)
1
iv) cmp(): Compares the elements of lists.
>>>list1= [123, ‘xyz’]
>>>list2= [456, ‘abc’]
>>>print cmp(list1, list2)
-1
>>>print cmp(list2, list1)
1
>>> list2.append(786)
>>>print cmp(list2, list1)
-1
v) sum(): It returns the sum of all elements in a list.
>>>a= [5,10,15,5,4]
>>>sum(a)
39
vi) sorted(): Returns the sorted list of elements in ascending order.
>>>a= [5,10,15,4]
>>>sorted(a)
[ 4, 5, 10, 15 ]

Downloaded by sai shan3003 ([email protected])


lOMoARcPSD|24825242

List loop [Traversing a loop]


The most common way to traverse elements of a list is using for loop. The looping in a
list is done by for loop. There are two types of for looping
i) for-sequence (for-in-loop)
ii) for-range()
i) for-sequence
for loop is used to read elements of list.
Example:
>>>for i in [ 2, 3, 5, 6, 9 ] :
print ( i )
Output:
2
3
5
6
9
ii) for-range
To update elements of list, we need to specify the range.
Example Program1:
>>>for i in range(0,4):
print( i )
0
1
2
3
List mutability
The list is a mutable data structure, that means its elements can be replaced, inserted and
removed. A slice operator on the left side of an assignment operation can update single or
multiple elements of a list. New elements can be added to the list using append() method. Also
mutability is the ability of data to be changed without entirely recreating it.

Downloaded by sai shan3003 ([email protected])


lOMoARcPSD|24825242

Example:
>>>for i in range(0,4)
data[i]=[0]*3
>>>data
[0,0,0],[0,0,0],[0,0,0],[0,0,0],[0,0,0]
>>>data[1][1]
0
>>>data[2][2]
0
>>>data[1][1] = 8
>>>data[2][2] = 7
>>>data[3][0] = 6
>>>data
[0,0,0],[0,8,0],[0,0,7],[6,0,0],[0,0,0]
List aliasing
List aliasing is defined as circumstance where two (or) more variables refer to the same object.
In this example, a is assigned to b then both variables refers to same objects.
Example:
>>>a=[1,2,3] a
>>>b=a [1,2,3]
>>>b is a b
True
Here, the same list has two different names (‘a’ and ‘b’), so it is aliased. If the aliased object is
mutable, modifications done in one object affect the other object also.
Aliasing with mutable object:
Lists are mutable (changeable)
Example:
>>>a=[1,2,3]
` >>>b=a
>>>a

Downloaded by sai shan3003 ([email protected])


lOMoARcPSD|24825242

[1,2,3]
>>>b
[1,2,3]
>>>a[0]=10
>>>a
[10,2,3]
>>>b
[10,2,3]
Aliasing with immutable objects:
Strings, tuples are immutable (not changeable)
Example:
>>>a=’python
>>>b=a
>>>a[0]=c
Output:
‘Error’
Cloning list
Assignment statements in Python do not copy objects. They simply create bindings between
two objects. For mutable sequences (like lists), a copy of an existing object may be required so
that one object can be changed without affecting another. In lists, cloning operation can be used
to create a copy of an existing list so that changes made in one copy of list will not affect
another. The copy contains the same elements as the original. This can be done using
i) list() function
ii) copy() function
iii) copy.deepcopy() function

i) list() function
built-in list() function can be used for cloning lists with the following syntax
Syntax:
newlistname= list(oldlistname)

Downloaded by sai shan3003 ([email protected])


lOMoARcPSD|24825242

Example:
>>>a= [1,2,3]
>>>b= list(a)
>>>a
[1,2,3]
>>>b
[1,2,3]
>>>a[0]=4
>>>a
[4,2,3]
>>>b
[1,2,3]
ii) copy() function
copy.copy() is little slower than list() since it has to determine data type of old list first.
Syntax:
newlistname= copy.copy(oldlistname)
Example:
>>>import copy
>>>a= [1,2,3]
>>>b= copy.copy(a)
>>>a
[1,2,3]
>>>b
[1,2,3]
iii) copy.deepcopy() function
copy.deepcopy() is the slowest and memory-consuming method.
Syntax :
newlistname = copy.deepcopy(Oldlistname)
Example Program1:
import copy

Downloaded by sai shan3003 ([email protected])


lOMoARcPSD|24825242

oldlist = [10, 20, 30, 40, 70]


newlist = copy.deepcopy(oldlist) # Returns a deep copy of oldlist
print ‘Old list is : ‘, oldlist
print ‘New list is : ‘, newlist
Output:
Old list is : [10, 20, 30, 40, 70]
New list is : [10, 20, 30, 40, 70]
List parameters
A list can be passed as a parameter to a function. This parameter is passed by reference.
Changes made in list inside function will affect list even after returning function.
Example Program1: To circulate values of n variable .
def circulate(1,n):
newlist= l[[n:]+ l[n:]
return newlist
list= [1,2,3,4,5]
program(“original list:”, list)
mylist= circulate(list,1)
print(“list circulated clockwise by 1:”, mylist)
mylist= circulate(list, 2)
print(“List circulated clockwise by 2:”, mylist)
mylist= circulate(list, 3)
print(“List circulated clockwise by 3:”, mylist)
mylist= circulated(list, 4)
print(“List circulated clockwise by 4:”, mylist)
Output:
Original list: [1,2,3,4,5]
list circulated clockwise by1:[2,3,4,5,1]
list circulated clockwise by 2:[3,4,5,1,2]
list circulated clockwise by 3:[4,5,1,2,3]
list circulated clockwise by 4:[5,1,2,3,4]

Downloaded by sai shan3003 ([email protected])


lOMoARcPSD|24825242

Here list is passed as parameter to function (circulate), this list is circulated based on the value
passed as second parameter.
Deleting list elements
To remove a list element, del operator can be used if an element to be deleted is known.
In the following code, the element ‘Chennai’ is deleted by mentioning its index in the del
operator.
Example Program:
stulist = [‘Rama’, ‘Chennai’, 2018, ‘CSE’, 92.7]
print ‘Initial list is : ‘, stulist
del stulist[1]
print ‘Now the list is : ‘, stulist
Output:
Initial list is : [‘Rama’, ‘Chennai’, 2018, ‘CSE’, 92.7]
Now the list is : [‘Rama’, 2018, ‘CSE’, 92.7]
pop() and remove() methods can also be used to delete list elements.
TUPLES
Tuple is a collection of values of different types. Tuple values are indexed by integers.
The important difference is that tuples are immutable. Tuples are created using parenthesis ().
i) The values in tuples can be any type and they are indexed by integers
ii) A type is a comma-seperated list of values.
Example:
>>>t=’a’,’b’,’c’,’d’,’e’
Creation of tuples:
i) Create a tuple with a single element.
>>>t1= ‘a’
>>>type(t1)
<class ‘tuple’>
>>>t2=(‘a’)
>>>type(t2)
<class ‘str’>

Downloaded by sai shan3003 ([email protected])


lOMoARcPSD|24825242

ii) A tuple can be created using the built-in function tuple. It can create an empty tuple
with no argument.
>>>t= tuple()
>>>t
()
iii) A tuple built-in- functions can be used to create a tuple with sequence of arguments.
>>>t= tuple(‘computer’)
>>>t
(‘c’,’o’,’m’,’p’,’u’,’t’,’e’,’r’)
Operators on tuple:
i) Bracket operator
ii) Slice operator
iii) Relational operator
i) Bracket operator
Bracket operator indexes an element.
>>>t= (‘c’,’o’,’m’,’p’)
>>>t[0]
‘c’
>>>t[3]
‘p’
ii) Slice operator
Slice operator selects a range of elements.
>>>t[0:3]
(‘c’,’o’,’m’)
iii) Relational operator
The relational operators work with tuples and other sequences.
Python starts by comparing the first element from each sequence.
If they are equal, it goes on to the next elements and so on, until it finds elements that
differ.
Subsequent elements are not considered.

Downloaded by sai shan3003 ([email protected])


lOMoARcPSD|24825242

Example:
>>>(5,8,2)<(5,10,6)
True
>>>(3,2,500000)<(3,8,5)
True
Tuple assignment
Python has a very powerful tuple assignment feature that allows a tuple of variables on
the left of an assignment to be assigned values from a tuple on the right of the assignment.
Example 1:
>>>a,b= 5,10
>>>a
5
>>>b
10
Example 2:
>>>[x,y] = [3,4]
>>>x
3
>>>y
4
The right side can be any kind of sequence (string, list or tuple).
Example 3:
>>>a,b= minmax(‘abcd’)
>>>a
‘a’
>>>b
‘d’
Example 4:
Simultaneous assignment require the number of variables on the left must match with the
number of elements in the tuple.
>>>a,b= 1,2,3

Downloaded by sai shan3003 ([email protected])


lOMoARcPSD|24825242

valueError: too man values to un pack

Downloaded by sai shan3003 ([email protected])


lOMoARcPSD|24825242

Example 5:
To split an email address into a username and a domain split keyword is used.
>>>addr=’[email protected]
>>>uname,domain= addr.split(‘@’)
Here, the return value from split is set of lists splits with symbol ‘@’, with two elements and the
first element is assigned to username, the second to domain
>>>uname
‘effie’
>>>domain
‘python.org’
Tuples as return values
A function can return only one value, but if the value is a tuple, it can return multiple
values. Dividing two integers compute the quotient and remainder. It is inefficient to compute
x/y and then x%y. Python can compute both in the same time. The built-in function divmod takes
two arguments and returns a tuple of two values, the quotient and the remainder. Here the type of
returning a values are
i)It can store the result as a tuple.
>>>t= divmod(13,4)
>>>t
(3,1)
ii) To store the elements separately, use tuple assignment.
>>>Q,R= divmod(13,4)
>>>Q
3
>>>R
1
iii) A function can return a tuple. The built-in function def minmax(t) is used to find the
largest and smallest elements of a sequence and can return a tuple of two values.
def minmax(t):
return min(t),max(t)

Downloaded by sai shan3003 ([email protected])


lOMoARcPSD|24825242

max and min are built-in functions that find the largest and smallest elements of the
sequence.
minmax computes both the largest and smallest elements and returns a tuple of two
values.
Example Program:
>>>def minmax(t):
return min(t), max(t)
>>>minmax([6,3,7,12])
(3,12)
>>>minmax(‘abcd’)
(‘a’,’b’)
Accessing values
To access the tuple elements slicing (bracket operator [ ]) operator along with index or
indices is used.
Example Program:
t1 = (‘C’, ‘C++’, ‘python’, 1999, 2018);
t2 = (1, 2, 3, 4, 5, 6, 7 );
t3= (‘a’, ‘b’, ‘c’, ‘d’, ‘e’)
print “tup1[0]: “, tup1[0]
print “tup1[1]: “, tup1[1]
print “tup2[1:5]: “, tup2[1:5]
print “tup2[1:]: “, tup2[1:]
print t[0]
Output:
tup1[0]: C
tup1[1]: C++
tup2[1:5]: [2, 3, 4, 5, 6, 7]
a

Downloaded by sai shan3003 ([email protected])


lOMoARcPSD|24825242

Delete tuple elements


It is impossible to delete a single element in the tuple. There is, of course, nothing wrong
with putting together another tuple with the undesired elements discarded. To delete an entire
tuple, the keyword del is used.
Example Program:
t1 = (‘C’, ‘C++’, ‘python’, 1999, 2018);
print t1
del t1
print “After deleting : “
print t1
Output:
(‘C’, ‘C++’, ‘python’, 1999, 2018)
After deleting:
Traceback (most recent call last):
File “main.py”, line 5, in
print t1
NameError: name ‘t1’ is not defined
Updating tuples
Tuples are immutable means that the tuple values cannot be updated or changed.
However, the portions of existing tuples are added with a new tuple to create another tuple as the
following example demonstrates. Consider the following tuple,
t3= (‘a’, ‘b’, ‘c’, ‘d’, ‘e’)
No elements can be modified. If you try to modify, you will get an error.
t3[1]= ‘B’
TypeError: ‘tuple’ object does not support item assignment
Instead of modifying an element in the tuple sequence, it is obvious to simply replace one tuple
with another:
t3 = (‘A’) + t3 [1:]
print t

Downloaded by sai shan3003 ([email protected])


lOMoARcPSD|24825242

Output:
(‘A’, ‘b’, ‘c’, ‘d’, ‘e’)
Here, the first element ‘a’ is replaced with ‘A’. A new tuple is created with the value ‘A’ is
combined with tuple t3 having index from 1 to the last element. The tuple value t3[0]=’a’ is
replaced by ‘A’.
Built-in functions with tuple
The built-in functions with tuples are given below.
i) all(): Return True if all elements of the tuple are true (or if the tuple is empty).
ii) any():Return True if any element of the tuple is true. If the tuple is empty, return False.
iii) enumerate():Return an enumerate object. It contains the index and value of all the items of
tuple as pairs.
iv) len():Return the length (the number of items) in the tuple.
v) max():Return the largest item in the tuple.
vi) min():Return the smallest item in the tuple
vii) sorted():Take elements in the tuple and return a new sorted list (does not sort the tuple
itself).
viii) sum():Return the sum of all elements in the tuple.
Comparing tuples
With relational operators it is possible to work with tuples and other sequences. To
compare two elements, Python starts by comparing the first element from each sequence. If the
elements are equal, it goes on to the next elements, and so on, until it finds an element that is
different, subsequent elements are not considered (even if they are really big)
>>> (0, 1, 2) < (0, 3, 4)
True
DICTIONARIES
Dictionary is a collection of key-value pair, enclosed by curly braces { }, separated by
commas. The collection of indices are called keys for the collection of values. Each key is
associated with a single value. The association of a key and a value is called a key-value pair or
an item. The relationship between the key of one set that corresponds to a value of another set is
called mapping.

Downloaded by sai shan3003 ([email protected])


lOMoARcPSD|24825242

Dictionary is a mutable list.


 Dictionaries in Python are implemented using hash table. It is an array whose indexes
are obtained using a hash function on the keys.
A hash function takes a key value and returns hash value, an integer. This hash value
is used in the dictionary to store and lookup key-value pairs. So keys in dictionary must be
hashable.
Example 1:
>>>d={1:apple’,2:’ball’}
>>>d
{1:apple’,2:’ball’}
>>>d[1]
apple
>>>d[2]
Ball
Example 2:
>>>d={‘name’,:’ABCD’,’phoneno’,:04652}
>>>d[name]
ABCD
>>>d[phone no]
04652
>>>for key , val in d.items():
print (val:key)
name: ABCD
phoneno: 04652
The following code is a simple example which creates an empty dictionary.
mydict = {}
print mydict
Output:
{}

Downloaded by sai shan3003 ([email protected])


lOMoARcPSD|24825242

Dictionary –Operations and Methods.


The following dictionary operations and methods are used in python programming.
i) dict()
ii) dict(s)
iii) len()
iv) max()
v) min()
vi) all()
vii) sorted()
viii) any()
ix) pop()
x) copy()
xi) key()
xii) values()
xiii) update()
xiv) clear()
i) dict() : It creates a new, empty dictionary.
>>>cse=dict()
ii) dict(s): It creates a new dictionary with key-value.
>>>cse=dict(s)
iii) len(): It counts the number of key value pairs.
>>>cse={‘name’:’ABC’,’age’:20}
>>>len(cse)
2
iv) max(): It returns the maximum key in dictionary.
>>>max(cse)
‘name’
v) min(): It returns the minimum key in dictionary.
>>>min(cse)
‘age’

Downloaded by sai shan3003 ([email protected])


lOMoARcPSD|24825242

vi) all(): It returns true if all keys are true.


>>>all(cse)
True
vii) sorted(): It sort keys in order.
>>>sorted(cse)
[age’,’name’]
viii) any(): It returns true if any key is true
>>>any(cse)
True
ix) pop(): It removes particular item from dictionary.
>>>cse.pop(age)
>>>cse
{‘name’:’ABC’}
x) dict.copy(): It copies dictionary into new dictionary.
>>>cse={‘name’:’ABC’,’age’:’20’}
xi) dict.key(): It returns keys in dictionary
>>>dict.key(cse)
‘name’,’age’
xii) dict.values(): It returns values in dictionary.
>>>dict.values(cse)
‘ABC’,20
xiii) dict.update(): It adds dictionary key-value pairs to dictionary.
>>>dict.update(cse,”address”:”xyz”)
>>>cse
{‘name:’’ABC’,’age’:220,”address’:”xyz}
xiv) dict.clear(): It clears dictionary.
>>>dict.clear(cse)
>>>cse
{}

Downloaded by sai shan3003 ([email protected])


lOMoARcPSD|24825242

Access, update, and add elements in dictionary


Key can be used either inside square brackets or with the get() method. The difference
while using get() is that it returns none instead of KeyError, if the key is not found. Dictionary is
mutable. So we can add new items or change the value of existing items. If the key is present, its
value gets updated, else a new key: value pair is added to dictionary.
Delete or remove elements from a dictionary
A particular item in a dictionary can be removed by using the method pop(). This
method removes an item with the provided key and returns the value. The method, popitem()can
be used to remove and return an arbitrary item (key, value) from the dictionary. All the items can
be removed at once using the clear () method.
Sorting a dictionary
The items in dictionary can be sorted using sorted () function. In the following example,
fromkeys() function is used to create a dictionary from sequence of values. The value 10 is
assigned for all keys. Each item is accessed iteratively using for loop that iterate though each key
in a dictionary.
Example Program:
marks={}.fromkeys([‘Math’,’English’,’Science’],10)
print marks
for item in marks.items():
print item
print list(sorted(marks.keys()))
Output:
{‘Maths’: 10, ‘Science’: 10, ‘English’: 10}
(‘Maths’, 10)
(‘Science’, 10)
(‘English’, 10)
[‘English’, ‘Maths’, ‘Science’]
Reverse lookup
Lookup is the process of finding the corresponding value for the given key from
dictionary. It’s easy to find the value given a key to a Python dictionary.

Downloaded by sai shan3003 ([email protected])


lOMoARcPSD|24825242

value=dict[key]
Reverse lookup is the process of finding the key for a given value. The following function takes
a value and returns the first key that map to that value.
Example Program:
def getvalue(dic,value):
for name in dic:
if dic[name] == value:
return name
squares={1:1,2:4,3:9,4:16,5:25}
print getvalue(squares,4)
Output:
2
Inverting a dictionary
A dictionary can be inverted with list values. For example, if you were given a dictionary
that maps from child to parent, you might want to invert it; that is, create a dictionary that maps
from parent to children. Since there might be several children with the same parent each value in
the inverted dictionary should be a list of children.
Example Program:
def invertdict(d):
newdict = {}
for k, v in d.iteritems():
newdict.setdefault(v, []).append(k)
return newdict
d = { ‘child1’: ‘A1’,
‘child2’: ‘A1’,
‘child3’: ‘parent2’,
‘child4’: ‘parent2’ }
print invertdict(d)
Output:
{‘parent2’: [‘child3’, ‘child4’], ‘A1’: [‘child1’, ‘child2’]}

Downloaded by sai shan3003 ([email protected])


lOMoARcPSD|24825242

ADVANCED LIST PROCESSING


.The list comprehension is the advanced list processing is given below.
List comprehensions
List comprehension is an elegant and concise way to create new list from existing list in
python. List comprehension process is described by series of keywords.
Syntax:
[expression for item in list if conditional]
This is equivalent to:
for item in list:
if conditional:
expression
new_list = [expression(i) for i in oldlist if filter(i)]
newlist is the resultant list. expression (i) is the variable used for each element in the old list.
A list comprehension consists of the following parts:
i) An input sequence.
ii) Variable representing members of the input sequence.
iii) An optional predicate expression.
iv) An Output expression with members of the input sequence that satisfy the predicate.
Example Program1:
>>>a=[11,22,33,44]
>>>b=[x*2 for x in a]
>>>b
[22,44,66,88]
Example Program2:
>>>names=[‘alice’,’bob’,’charly’]
>>>b=[ name.upper() for name in names]
>>> b
[‘ALICE’,’BOB,’CHARLY]
>>>c=[name.capitalize() for name in names]
[‘Alice’,’Bob’,’Charly’]

Downloaded by sai shan3003 ([email protected])


lOMoARcPSD|24825242

Example Program3:
>>>vowels=(‘a’,’e’,’i’,’o,’u’)
>>>t=’hello’
>>>[c for c in t if c in vowels]
[‘e’,’o’]
Example Program4:
>>>a=[1,2,3,4]
>>>[x**2 for x in a]
[1,4,9,16]
Example Program5:
>>>a= [10,5,0,-5,-10]
>>>[x for x in a if x>0]
[10,5]
>>>[x for x in a if
x<0] [-5,-10]

ILLUSTRATIVE PROGRAMS
Insertion sort
def insertionsort(a):
for index in range(1,len(a)):
currentvalue=a[i]
position=i
while position>0 and a[position-1]>currentvalue:
a[position]=a[position-1]
position=position-1
a[position]=currentvalue
list=[50,60,40,30,20,70]
print( “Original list is:”,list)
insertionsort(list)
print(”Sorted list is:”,a)

Downloaded by sai shan3003 ([email protected])


lOMoARcPSD|24825242

Output:
Original list is: [50,60,40,30,20,70]
Sorted list is: [20,30.40,50,60,70]
Selection sort
def selectionSort(alist):
for i in range(len(alist)-1,0,-1):
pos=0
for location in range(1,i+1):
if alist[location]>alist[pos]:
pos= location
temp = alist[i]
alist[i] = alist[pos]
alist[pos] = temp

alist = [54,26,93,17,77,31,44,55,20]
print( “Original list is:”, alist)
selectionSort(alist)
print( “Sorted list is: “, alist)
Output:
Original list is : [54,26,93,17,77,31,44,55,20]
Sorted list is: [17, 20, 26, 31, 44, 54, 55, 77, 93]
Merge sort
def mergesort(a):
if len(a)>1:
mid=len(a)//2
left=a[:mid]
right=a[mid:]
mergesort(left)
mergesort(right)

Downloaded by sai shan3003 ([email protected])


lOMoARcPSD|24825242

i=0
j=0
k=0

while i<len(left) and j<len(right):


if left[i]<right[j]:
a[k]=left[i]
i=i+1
else:
a[k]=right[j]
j=j+1
k=k+1
while i<len(left):
a[k]=left[i]
i=i+1
k=k+1
while j<len(right):
a[k]=right[j]
j=j+1
k=k+1

list=[50,60,40,20,70,100]
print ("Original list is:" ,list)
mergesort(list)
print ("Sorted list is:",list)
Output:
Original list is: [50, 60, 40, 20, 70, 100]
Sorted list is: [20, 40, 50, 60, 70, 100]

Downloaded by sai shan3003 ([email protected])


lOMoARcPSD|24825242

Histogram
histogram = [2,8,4,3,2]
for n in histogram:
output=’’
for i in range(n):
output+=’*’
print(output)
Output:
**
********
****
***
**
Students mark statement
def displayData():
print ("Roll Number is: ", r)
print ("Name is: ", name)
print ("Marks are: ", m1, m2, m3)
print ("Total Mark is: ", total())
print ("Average Mark is: ", average())

def total():
return (m1 + m2 + m3)

def average():
return ((m1 + m2 + m3) / 3)

r = int (input("Enter the roll number: "))


name = input("Enter the name: ")
m1 = int (input("Enter the marks in the first subject: "))

Downloaded by sai shan3003 ([email protected])


lOMoARcPSD|24825242

m2 = int (input("Enter the marks in the second subject: "))


m3 = int (input("Enter the marks in the third subject: "))
displayData()
Output:
Enter the roll number: 001
Enter the name: Aruna
Enter the marks in the first subject: 98
Enter the marks in the second subject: 90
Enter the marks in the third subject: 94
Roll Number is: 001
Name is: Aruna
Marks are: 98 90 94
Total Mark is: 282
Average Mark is: 94.0
Retail bill preparation
product1_name, product1_price = "Books", 50.95
product2_name, product2_price = "Computer", 598.99
product3_name, product3_price = "Monitor", 156.89
company_name = "ACEW."
company_address = "Manavilai."
company_city = "Tamil Nadu,India."
message = "Thanks for shopping with us today!"

print('*' * 50)
print("\t\t ", company_name)
print("\t\t ", company_address)
print("\t\t ", company_city)

print('-' * 50)
print("\tProduct Name\tProduct Price")

Downloaded by sai shan3003 ([email protected])


lOMoARcPSD|24825242

print("\t ", product1_name, "\t ", product1_price)


print("\t ", product2_name, "\t ", product2_price)
print("\t ", product3_name, "\t ", product3_price)

print('=' * 50) print("\


t\t\t Total")
total = product1_price + product2_price + product3_price
print("\t\t\t ", total)
print('-' * 50)
print("\t ", message)
Output:
**************************************************
ACEW.
Manavilai.
Tamil Nadu,India.

Product Name Product Price


Books 50.95
Computer 598.99
Monitor 156.89
============================================
Total
806.83

Thanks for shopping with us today!

Downloaded by sai shan3003 ([email protected])


lOMoARcPSD|24825242

MODULES
Module is a file containing Python definitions and statements. Modules are
imported from other modules using the import command.
i) When module gets imported, Python interpreter searches for module.
ii) If module is found, it is imported.
iii) If module is not found, “module not found” will be displayed.

Modules

Built- in module User defined


modules

random math date time

Fig 5.3: Types of modules


Built-in modules
Built- in modules are predefined modules, which is already in python standard
library.
Python have the following built-in modules.
i) random
This module generates random numbers. If we want random integer, we use randint
function.
Example:
>>>import random
>>>print random .
randint(0,5) 1
(or)2 (or) 3
(or)4 (or)5
ii) math

Downloaded by sai shan3003 ([email protected])


lOMoARcPSD|24825242

This module is used for mathematical calculations. If we want to calculate square


root, we use the function sqrt.
Example:
>>>import math
>>>m
ath
.
sqr
t(1
6)
4

>>>math
.
factor
ial(4)
24
iii) datetime
This module is used to calculate date and time.
Example:
>>>import datetime
>>>datetime .
time()
9:15:20

>>>date
time
.
date(
)
21.06

Downloaded by sai shan3003 ([email protected])


lOMoARcPSD|24825242

.2018
User Defined modules
To create module,write one or more functions in file, then save it with .py extentions.
i) Create a file
def
a
d
d
(
a
,
b
)
:
c
=
a
+
b
return c
ii) Save it as sum.py
iii) Import module
>>>import sum
>>>print sum.add(10,20)
PACKAGES
When we have a large number of Python modules, they can be organized
into packages such that similar modules are placed in one package and different
modules are placed in different packages. A package is a tree like hierarchical file
directory structure that consists of modules, sub-packages, sub-sub packages, and so
on. In another words, it is a collection of modules. When a package is imported,

Downloaded by sai shan3003 ([email protected])


lOMoARcPSD|24825242

Python explores in list of directories on sys.path for the package subdirectory.


Example:
Assume we are creating a package named Animals with some sub packages as shown
in following.

Animals

(Package)

_init_.py Mammals Birds

(Module) (Sub-Package) (Sub-Package)

_init_.py _init_.py

(Module) (Module)

create.py create.py

(Module) (Module)

print.py display.py

(Module) (Module)

Fig 5.3: Organization of packages and modules


Steps to create a Python package:
i) Create a directory and name it with a package name.
ii) Keep subdirectories (sub packages) and modules in it.
iii) Create init .py file in the directory
This init .py file can be left empty but we generally place the initialization code
with import statements to import resources from a newly created package. This file is

Downloaded by sai shan3003 ([email protected])


lOMoARcPSD|24825242

necessary since Python will know that this directory is a Python package directory
other than an ordinary directory.
Method 1:
Consider, we import the display.py module in the above example. It is
accomplished by the following statement.

Syntax:
import Animals.Birds.display
Now if this display.py module contains a function named displayByName(),
we must use the following statement with full name to reference it.
Syntax:
Animals.Birds.display.displayByName()
Method 2:
On another way, we can import display.py module alone as follows:
Syntax:
from Animals.Birds import display
Then, we can call displayByName() function simply as shown in the following
statement:
Syntax:
display.displayByName()

Downloaded by sai shan3003 ([email protected])

You might also like