UNIT IV (1)
UNIT IV (1)
4.1. Lists
Empty List
>>> list=[ ]
>>> list
[]
Integer List
>>> list1=[1,2,3]
>>> list1
[1, 2, 3]
List with mixed data types
>>> list2=[10,25.5,'prema']
>>> list2
[10, 25.5, 'prema']
Nested List
>>> list4=["selvi",
[10,20,30],'prema']
>>> list4
['selvi', [10, 20, 30], 'prema']
Example
>>> list=[10,20,30,40,50]
>>> print(list[0])
10
>>> print(list[3])
40
>>> list=['a', 'b', 'c', 'd']
>>> list[3]
'd'
>>> list=['Tamil', 'Kavi',
'Duraisamy']
>>> print(list[2])
Duraisamy
>>> list4=["Kavitha",
[10,20,30],'Tamil']
>>> list4[0]
'Kavitha'
>>> list4[0][0]
'K'
>>> list4[1][0]
10
>>> list4[2][0]
'T'
i) Concatenation
Example
>>> list1=[10,20,30,40,50]
>>> list2=['a','b','c']
>>> list1+list2
>>> list1+list2+list3
[10, 20, 30, 40, 50, 'a', 'b', 'c', 'Tamil', 'kavi', 'duraisamy']
ii. Repetition
Repetition operator is used to repeat the list for given number of times.
Operator used for repetition is asterisk (*) operator.
Example
>>> list2=['a','b','c']
>>> list1*2
[10, 20, 30, 40, 50, 10, 20, 30, 40, 50]
>>> list2*3
User can access a range of items in a list by using the slicing operator
colon (:). A subsequence of a sequence is called a slice and the operation that
extracts a subsequence is called slicing. Like with indexing, we use square
brackets ([ ]) as the slice operator, but instead of one integer value inside we
have two, separated by a colon (:). Python also allows slicing of the lists. User
can access a part of complete list by using index range.
Syntax
list_name[start:end]
Example
>>> list=[10,20,30,40,50,60,70]
>>> list[0:5]
>>> list[2:6]
>>> list[:3]
>>> list[1:]
>>> list[:]
>>> list[:-5]
[10, 20]
>>> list[-2:]
[60, 70]
4.1.3. List Methods
Methods that are available with list object in Python programming are
tabulated below. They are accessed as list.method(). Some of the methods
have already been used above.
Built-in Functions
i. append( )
The method list.append(x) will add an item (x) to the end of a list.
Appends object obj to list.
Example
>>> list=[10,20,30]
>>> list.append(40)
>>> list
[10, 20, 30, 40]
ii. insert( )
Example
>>> list=['a','c','d','e']
>>> list.insert(1,'b')
>>> list
['a', 'b', 'c', 'd', 'e']
iii. count( )
The list.count(x) method will return the number of times the value x
occurs within a specified list. Return the count of number of items passed as
an argument.
Example
>>> list=[1,1,2,3,4,'a','a','b','tamil']
>>> list.count(1)
2
>>> list.count('tamil')
1
iv. extend( )
If user want to combine more than one list, then user can use the
list.extend(L) method, which takes in a second list as its argument. Add all
elements of a list to the another list.
Example
>>> list1=['tamil','kavi']
>>> list2=['duraisamy','sivalingam','amma']
>>> list1.extend(list2)
>>> list1
['tamil', 'kavi', 'duraisamy', 'sivalingam', 'amma']
v. index( )
Method used to return the index of the first matched item in the list.
When lists start to get long, it becomes more difficult for us to count out our
items to determine at what index position a certain value is lo-cated. We can use
list.index(x), where x is equivalent to an item value, to return the index in the list
where that item is located. If there is more than one item with value x, this
method will return the first index location.
Example
>>> list=[1,1,2,4,5,3,1,1,3,5,3]
>>> list.index(1)
0
>>> list.index(3)
5
>>> list.index(7)
ValueError: 7 is not in list
vi. remove( )
Method used to remove an element from the list. When user need to
remove an item from a list, remove(x) method which removes the first item
in a list whose value is equivalent to x can be used.
Example
>>> list=['cse','ece','eee','eie','civil']
>>> list.remove('eie')
>>> list
['cse', 'ece', 'eee', 'civil']
vii. pop( )
Method used to remove and returns an element removed from the list.
User can use the list.pop([i]) method to return the item at the given index
position from the list and then remove that item.
Example
>>> list=['cse','ece','eee','eie','civil']
>>> list.pop(3)
'eie'
>>> list
['cse', 'ece', 'eee', 'civil']
viii. reverse( )
Method used to reverse the order of items in the list. User can reverse
the order of items in a list by using the list.reverse() method. Perhaps it is
more convenient for us to use reverse alphabetical order rather than
traditional alphabetical order.
Example
>>> list=['b','z','a','c','e']
>>> list.reverse()
>>> list
['e', 'c', 'a', 'z', 'b']
>>> list2=[10,20,30,40]
>>> list2.reverse()
>>> list2
[40, 30, 20, 10]
ix. sort( )
Method used to sort items in a list in ascending order. User can use the
list.sort() method to sort the items in a list.
Example
>>> list=['b','z','a','c','e']
>>> list.sort()
>>> list
['a', 'b', 'c', 'e', 'z']
>>> list2=[20,40,10,50,30]
>>> list2.sort()
>>> list2
[10, 20, 30, 40, 50]
x. clear( )
Example
>>> list=[20,40,10,50,30]
>>> list
[20, 40, 10, 50, 30]
>>> list.clear()
>>> list
[]
xi. copy( )
Method used to copy elements of the list. When user working with a
list and may want to manipulate it in multiple ways while still having the
original list available to us unchanged, user can use list.copy() to make a
copy of the list.
Example
>>> list=['tamil','kavi','selva','durai']
>>> new=list.copy()
>>> new
['tamil', 'kavi', 'selva', 'durai']
4.1.4 List Loop
User use a loop to access all the elements in a list. A loop is a block of
code that repeats itself until it runs out of items to work with, or until a
certain condition is met. In this case, our loop will run once for every item in
our list. With a list that is three items long, our loop will run three times.
Using a “for” loop user can iterate though each item in a list. It has the ability
to iterate over the items of any sequence, such as a list or a string.
Syntax
statements(s)
Flowchart
for iterating_var in
sequence:
If no more item in
Item sequence
from Next
sequenc statement
e
True
Red
Blue
Green
Yellow
Pink
Lists are mutable, which means user can change their elements.
Using the bracket operator on the left side of an assignment, user can update
one of the elements.
Example
>>> list=['red','blue','green','white']
>>> list
['red', 'blue', 'green', 'white']
>>> list[3]='black'
>>> list
['red', 'blue', 'green', 'black']
>>> str="TEST"
>>> str
'TEST'
>>> str[2]="X"
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'str' object does not support item
assignment
>>> list1=['T','E','S','T']
>>> list[2]='X'
>>> list1[2]='X'
>>> list1
['T', 'E', 'X', 'T']
>>> a=['a','b','c','d','e','f']
>>> a
['a', 'b', 'c', 'd', 'e', 'f']
>>> a[1:3]=['z','x']
>>> a
['a', 'z', 'x', 'd', 'e', 'f']
User can also remove elements from a list by assigning the empty list to
them:
>>> a
['a', 'z', 'x', 'd', 'e', 'f']
>>> a[1:3]=[]
>>> a
['a', 'd', 'e', 'f']
Mutable list allows users to delete list element using del keyword
>>> name=['tamil','selva','kavi']
>>>name
['tamil', ‘selva’, 'kavi']
>>> del name[1]
>>> name
['tamil', 'kavi']
4.1.6. List Aliasing
Alias name is used to indicate that a named list is also known or more
familiar under another specified name. Since variables refer to objects, if user
assign one variable to another, both variables refer to the same object.
Example
>>> a=[10,20,30]
>>> b=a
>>> b
[10, 20, 30]
>>> a is b
True
Both names indicate the same list. Changes made to the list with one name
are also reflected in another name. Alias provide two different names given
to one list.
Example
>>> a
[10, 20, 30]
>>> b[1]=25
>>> a
[10, 25, 30]
Syntax
new_list = old_list[:]
>>> list=[10,20,30]
>>> new=list[:]
>>> new
[10, 20, 30]
Taking any slice of a creates a new list. In this case the slice happens to
consist of the whole list. Changes made in new list will not reflect in old list
as like in alias. Now we are free to make changes to new without worrying
about old list.
Example
>>> new[2]=25
>>> new
[10, 20, 25]
>>> list
[10, 20, 30]
Passing a list as an argument actually passes a reference to the list, not a copy of the list.
Since lists are mutable changes made to the parameter change the argument as well.
func(5, *some_list)
func(5, "some", "values", "in", "a", "list")
4.2. Tuples
Example
>>> tup=(10,20,30)
>>> print(tup)
(10, 20, 30)
>>> tup2=('a','b','c')
>>> tup2
('a', 'b', 'c')
>>> tup3=("tamil","selvan","kavi")
>>> tup3
('tamil', 'selvan', 'kavi')
>>> tup4=(10,20.5,'a',"tamil")
>>> tup4
(10, 20.5, 'a', 'tamil')
Example
>>>tup=(10,20,30,40,50)
>>>tup
(10,20,30,40,50)
>>> tup[1]=15
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'tuple' object does not support item
assignment
Example
>>> x,y=10,20
>>> print(x,y)
10 20
>>> x,y,z=10,20
ValueError: not enough values to unpack
(expected 3, got 2)
>>> x,y=10,20,30
ValueError: too many values to unpack
(expected 2)
Example
>>> x=10;y=20
>>> print(x,y)
10 20
>>> temp=x
>>> x=y
>>> y=temp
>>> print(x,y)
20 10
Example
>>> x,y=10,20
>>> print(x,y)
10 20
>>> x,y=y,x
>>> print(x,y)
20 10
4.2.3. Basic Tuples Operations
i. Concatenation
Example
>>> t1=(10,20.5,30)
>>> t2=('a','b','c')
>>> t3=('tamil','kavi')
>>> t1+t2+t3
(10, 20.5, 30, 'a', 'b', 'c', 'tamil', 'kavi')
ii. Repetition
Example
>>> t1=(10,20.5,'a','b','tamil')
>>> t1 * 2
(10, 20.5, 'a', 'b', 'tamil', 10, 20.5, 'a', 'b', 'tamil')
>>> t2=(1,2,3)
>>> t2 * 3
(1, 2, 3, 1, 2, 3, 1, 2, 3)
iii. Membership
Example
>>> t1=(10,20,30,40,50)
>>> print(10 in t1)
True
>>> print(6 in t1)
False
iv. Tuple Indexing
User can use the index operator [] to access an item in a tuple where
the index starts from 0. So, a tuple having 6 elements will have index from 0
to 5. Trying to access an element other that (6, 7,...) will raise an IndexError.
The index must be an integer, so we cannot use float or other types. This will
result into TypeError.
Example
>>> tuple=('t','a','m','i','l')
>>> print(tuple[0])
t
>>> print(tuple[3])
I
Python tuples allows negative indexing for its sequence. The index of -1
refers to the last item, -2 to the second last item and so on.
Example
>>> tuple=('t','a','m','i','l')
>>> print(tuple[-1])
l
>>> print(tuple[-3])
M
v. Tuple Slicing
User can access a range of items in a tuple by using the slicing
operator. Slicing operator in python language is colon(:).
Example
>>> tuple=('t','a','m','i','l')
>>> print(tuple[0:3])
('t', 'a', 'm')
>>> print(tuple[2:3])
('m',)
>>> print(tuple[2:])
('m', 'i', 'l')
>>> print(tuple[:])
('t', 'a', 'm', 'i', 'l')
>>> print(tuple[:-2])
('t', 'a', 'm')
vi. Deleting a Tuple
Example
>>> t=(10,20,30)
>>> print(t)
(10, 20, 30)
>>> del t
>>> print(t)
NameError: name 't' is not defined
Example
>>> t1=(10,20,30)
>>> t2=(5,15,25)
>>> t1>t2
True
>>> t1<t2
False
Function Description
Functions can always only return a single value, but by making that value
a tuple, we can effectively group together as many values as we like, and
return them together. In such case user create a single tuple which holds
multiple elements.
Example
def circleInfo(r):
""" Return (circumference, area) of a circle of radius r """
c = 2 * 3.14159 * r
a = 3.14159 * r * r
return (c, a)
print(circleInfo(10))
Output
G:\PYTHON\PROGRAM>python tupreturn.py
(62.8318, 314.159)
TUPLE LIST
Tuple is collection of different List is collection of different
data type values data type values
Tuple defined using parenthesis List defined using square
“( )” brackets “[ ]”
Tuples are immutable Lists are mutable
Values of tuple cannot be Values of list can be
changed or updated changed or updated
>>> list=[10,20,30]
>>> tup=(10,20,30) >>> print(list)
>>> print(tup) [10, 20, 30]
(10, 20, 30) >>> list[1]=40
>>> tup[1]=40 >>> print(list)
TypeError: 'tuple' object does [10, 40, 30]
not support item assignment
4.3 Dictionaries
Each key is separated from its value by a colon (:), the items are
separated by commas, and the whole thing is enclosed in curly braces. An
empty dictionary without any items is written with just two curly braces, like
this: { }.
Keys are unique within a dictionary while values may not be. The
values of a dictionary can be of any type, but the keys must be of an
immutable data type such as strings, numbers, or tuples.
Example 1
dict['Name']: Tamil
dict['Age']: 31
If user attempt to access a data item with a key, which is not part of
the dictionary
Example 2
b. Updating Dictionary
Example
>>> print(dict)
{'Name': 'Tamil', 'Age': 31, 'Class': 'First'}
>>> dict['Name']='Tamil Selvan' #Update existing value
>>> print(dict)
{'Name': 'Tamil Selvan', 'Age': 31, 'Class': 'First'}
>>> dict['Place']='Kavindapadi' #Add new entry into dictionary
>>> print(dict)
{'Name': 'Tamil Selvan', 'Age': 31, 'Class': 'First', 'Place':
'Kavindapadi'}
c. Delete Dictionary Elements
Example
>>> d1={'Name':'Tamil','Age':31,'Class':'First'}
>>> print(d1)
{'Name': 'Tamil', 'Age': 31, 'Class': 'First'}
>>> del d1['Class']
>>> print(d1)
{'Name': 'Tamil', 'Age': 31}
>>> d1.clear()
>>> print(d1)
{}
>>> del d1
>>> print(d1)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'd1' is not defined
(a) More than one entry per key not allowed. Which means no duplicate key
is allowed. When duplicate keys encountered during assignment, the last
assignment wins.
Example
>>> d1={'Name':'Tamil','Age':31,'Class':'First'}
>>> d1['Name']='Selva'
>>> d1
{'Name': 'Selva', 'Age': 31, 'Class': 'First'}
(b) Keys must be immutable. Which means you can use strings, numbers or
tuples as dictionary keys but something like ['key'] is not allowed.
4.3.3. Dictionary Methods
Methods that are available with dictionary are tabulated below. Some
of them have already been used in the above examples.
d1={'Name':'Tamil','Age':31}
Remove all items form >>> d1.clear()
clear()
the dictionary. >>> d1
{}
>>> d1
{'Name': 'Tamil', 'Age': 31}
Return a shallow copy
copy()
of the dictionary. >>> d1.copy()
{'Name': 'Tamil', 'Age': 31}
>>> d1.values()
Return a new view of
values() dict_values(['Tamil', 31,
the dictionary's values
'KVP'])
cmp(dict1, dict2)
1
Compares elements of both dict.
len(dict)
2 Gives the total length of the dictionary. This would be
equal to the number of items in the dictionary.
str(dict)
3 Produces a printable string representation of a
dictionary
type(variable)
Returns the type of the passed variable. If passed
4
variable is dictionary, then it would return a dictionary
type.
4.3.5. Advanced List Processing – List Comprehension
print(squares)
Output
G:\PYTHON\PROGRAM>python sam.py
squares = {}
for x in range(6):
squares[x] = x*x
print(odd_squares)
Output
G:\PYTHON\PROGRAM>python sam.py
User can test if a key is in a dictionary or not using the keyword in.
Notice that membership test is for keys only, not for values.
Output
True
True
False
for i in squares:
print(squares[i])
Output
G:\PYTHON\PROGRAM>python sam.py
1
9
25
49
81
4.4. Illustrative Programs
i. First Element
iii. So on
Example
Sort the following elements using Selection sort. 23, 78, 45, 8, 32, 56
1. Initial List
23 78 45 8 32 56
swap
2. Pass 1
8 78 45 23 32 56
swap
3. Pass 2
8 23 45 78 32 56
swap
4. Pass 3
8 23 32 78 45 56
swap
5. Pass 4
8 23 32 45 78 56
swap
6. Pass 5
8 23 32 45 56 78
Sorted List
Python Program
# Python program for implementation of Selection Sort
import sys
A = [64, 25, 12, 22, 11]
Output
G:\PYTHON\PROGRAM>python selection.py
Sorted array
11
12
22
25
64
4.4.2. Insertion Sort
Example
Sort the following elements using Insertion sort. 30, 70, 20, 40, 10, 60
30 70 20 40 10 60
30
70 20 40 10 60
30 70 20 40 10 60
20 30 70
40 10 60
20 30 40 70
10 60
10 20 30 40 70
60
10 20 30 40 60 70
key = arr[i]
Output
Merge sort is a sorting algorithm that uses divide and Conquer strategy. It is
an external sorting algorithm. Merge Sort is quite fast, and has a time
complexity of O(n log n). It is a stable sort, which means the "equal"
elements are ordered in the same order in the sorted list.
Divide Partition the given array into 2 sublists (s1 and s2).
Conquer Sort s1 and s2 separately.
Combine Finally combine sorted list together.
Example
Sort the following data using Merge Sort 70, 20, 30, 40, 10, 50, 60
70 20 30 40 10 50 60
70 20 30 40 10 50 60
70 20 30 40 10 50 60
70 20 30 40 10 50 60
20 70 30 10 40 50 60
20 30 70 10 40 50 60
10 20 30 40 50 60 70
Sorting using Merge Sort Algorithm
def mergeSort(alist):
print("Splitting",alist)
if len(alist)>1:
mid = len(alist)//2
lefthalf = alist[:mid]
righthalf = alist[mid:]
mergeSort(lefthalf)
mergeSort(righthalf)
i=0
j=0
k=0
while i < len(lefthalf) and j < len(righthalf):
if lefthalf[i] < righthalf[j]:
alist[k]=lefthalf[i]
i=i+1
else:
alist[k]=righthalf[j]
j=j+1
k=k+1
while i < len(lefthalf):
alist[k]=lefthalf[i]
i=i+1
k=k+1
while j < len(righthalf):
alist[k]=righthalf[j]
j=j+1
k=k+1
print("Merging",alist)
alist = [54,26,93,17,77,31,44,55,20]
mergeSort(alist)
print(alist)
Output
G:\PYTHON\PROGRAM>python mer.py
Splitting [54, 26, 93, 17, 77, 31, 44, 55, 20]
Splitting [54, 26, 93, 17]
Splitting [54, 26]
Splitting [54]
Merging [54]
Splitting [26]
Merging [26]
Merging [26, 54]
Splitting [93, 17]
Splitting [93]
Merging [93]
Splitting [17]
Merging [17]
Merging [17, 93]
Merging [17, 26, 54, 93]
Splitting [77, 31, 44, 55, 20]
Splitting [77, 31]
Splitting [77]
Merging [77]
Splitting [31]
Merging [31]
Merging [31, 77]
Splitting [44, 55, 20]
Splitting [44]
Merging [44]
Splitting [55, 20]
Splitting [55]
Merging [55]
Splitting [20]
Merging [20]
Merging [20, 55]
Merging [20, 44, 55]
Merging [20, 31, 44, 55, 77]
Merging [17, 20, 26, 31, 44, 54, 55, 77, 93]
[17, 20, 26, 31, 44, 54, 55, 77, 93]
4.4.4. Python program 1 for Histogram
histogram([2, 3, 6, 5])
Output
G:\PYTHON\PROGRAM>python hist.py
**
***
******
*****
import plotly.plotly as py
import plotly.graph_objs as go
import numpy as np
x = np.random.randn(500)
data = [go.Histogram(x=x)]
Output
4.4.6. Students marks statement
OUTPUT:
Case 1:
Enter marks of the first subject: 85
Enter marks of the second subject: 95
Enter marks of the third subject: 99
Enter marks of the fourth subject: 93
Enter marks of the fifth subject: 100
Grade: A
Case 2:
Enter marks of the first subject: 81
Enter marks of the second subject: 72
Enter marks of the third subject: 94
Enter marks of the fourth subject: 85
Enter marks of the fifth subject: 80
Grade: B
4.4.7. Retail bill preparation
print("\namount left", s)
else:
# append value of in "name", "quantity", "price"
na.append(pn)
OUTPUT
Enter Your budget : 500
1.Add an item
2.Exit
Enter your choice : 1
1.Add an item
2.Exit
Enter your choice : 1
1.Add an item
2.Exit
Enter your choice : 1
1.Add an item
2.Exit
Enter your choice : 1
1.Add an item
2.Exit
Enter your choice : 1
1.Add an item
2.Exit
Enter your choice : 2