PP Unit II Data Types Notes For Mc4103
PP Unit II Data Types Notes For Mc4103
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.
>>>msg1!=msg2
False
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.
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
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
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 :
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.
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
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’]
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]
>>>b=[4,5,6]
>>>a.extend(b)
>>>a
[1,2,3,4,5,6]
iii) sort()
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()
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()
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
[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)
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
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
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)
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
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.
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’]}
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")
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
>>>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,
Animals
(Package)
_init_.py _init_.py
(Module) (Module)
create.py create.py
(Module) (Module)
print.py display.py
(Module) (Module)
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()