PP Unit-Ii
PP Unit-Ii
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.
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.
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.
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.
Standard modules are imported the same way as we import user-defined modules.
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,
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
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
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.
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 :
>>>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 = []
>>>a= [1,2,3]
>>>a.index(2)
1
viii) count()
Syntax:
It counts how many times the elements occur in the list.
>>>a= [1,2,3,2]
>>>a.count()
2
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()
i) list() function
built-in list() function can be used for cloning lists with the following syntax
Syntax:
newlistname= list(oldlistname)
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
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]
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’>
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.
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
valueError: too man values to un pack
Example 5:
To split an email address into a username and a domain split keyword is used.
>>>addr=’effie@python.org’
>>>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)
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
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
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.
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:
{}
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’
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
{}
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.
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’]}
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’]
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)
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)
i=0
j=0
k=0
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]
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)
print('*' * 50)
print("\t\t ", company_name)
print("\t\t ", company_address)
print("\t\t ", company_city)
print('-' * 50)
print("\tProduct Name\tProduct Price")
print("\t ", product1_name, "\t ", product1_price)
print("\t ", product2_name, "\t ", product2_price)
print("\t ", product3_name, "\t ", product3_price)
Modules
>>>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
.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,
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 _init_.py
(Module) (Module)
create.py create.py
(Module) (Module)
print.py display.py
(Module) (Module)
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()