UNIT_IV_notes_Python
UNIT_IV_notes_Python
Lists: list operations, list slices, list methods, list loop, mutability, aliasing, cloning lists, list
parameters; Tuples: tuple assignment, tuple as return value; Dictionaries: operations and
methods; advanced list processing - list comprehension; Illustrative programs: simple
sorting, histogram, Students marks statement, Retail bill preparation.
LIST
A list is a versatile data type contains items separated by commas and enclosed within
square brackets ([ ]). An item can be of any type.
Each and every item has its unique index.
A list contains different data type such as string, integer, float, real and another list.
Example:
list=[2345,’bala’,70.8,'A’]
empty = [ ] #empty list
Nested list
A list within another list nested.
n=[‘saran’,’kalai’,[20,45,36]]
List Operations
1. Concatenation
2. Repetition
3. Membership operator
4. List Slice
(i) The + operator concatenates list.
EX:
a = [1, 2, 3]
b = [4, 5, 6]
c=a+b
print(c )
1
O/P:
[1, 2, 3, 4, 5, 6]
O/P:
==================RESTART:C:/Users/RAMPRIYA/Desktop/sa.py==============
True
False
False
List indexing
Positions are numbered from left to right starting at 0 and it is called as positive
indexing. Positions can also be numbered from right to left starting at -1 and it is called as
negative indexing.
0 1 2 3 4 5
P Y T H O N
-6 -5 -4 -3 -2 -1
Example
my_list = ['p','r','o','b','e']
print(my_list[0])
print(my_list[2])
print(my_list[4])
n_list = ['Happy',[2,0,1,5]]
print(n_list[0][1])
print(n_list[1][3])
my_list = ['p','r','o','b','e']
print(my_list[-1])
print(my_list[-5])
2
Output:
p
o
e
a
5
e
p
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.
3
print(list1)
list1.extend([10,20,30])
print(list1)
list2=[5,2,10,4]
list2.sort()
print(list2)
list2.reverse()
print(list2)
print(list2.index(2))
print(list2.pop(0))
del list2[2]
print(list2)
print(list2.count(4))
print(list2.clear())
Output:
[1, 2, 3, 4, 99]
[1, 100, 2, 3, 4, 99]
[1, 100, 2, 3, 99]
[1, 100, 2, 3, 99, 10, 20, 30]
[2, 4, 5, 10]
[10, 5, 4, 2]
3
10
[5, 4]
1
None
Infinite loop
4
A loop becomes infinite loop if a condition becomes FALSE. Such a loop is called as
infinite loop.
Example: client-server programming (server needs to run continuously so that client can
communicate with it)
Example:
i=1
while i==True:
print('Loop')
Output:
Loop
Loop
Loop
…..
…..
…..
LIST MUTABILITY:
Lists are mutable because the elements of the list can be altered or assigned.
Example:
numbers=[17,123]
numbers[0]=5
print(numbers)
Output:
[5, 123]
List aliasing
When two identifiers refer to the same variable or value, then it is called as aliasing.
This type of change is known as side effect. The variable one and two both refers to the
exact same list object. They are aliases for the same object.
Example.py
one=[10,20,30]
two=one
print(one)
print(two)
one[2]=55
print(one)
print(two)
Output:
[10, 20, 30]
[10, 20, 30]
[10, 20, 55]
[10, 20, 55]
List Cloning
It is a process of making a copy of the list without modifying the original list.
When changes are done, it is applied only in duplicate copy and not reflected to original
copy.
Example:
5
original=[20,45,12,36]
duplicate=original.copy()
duplicate[2]='rose'
print(original)
print(duplicate)
Output:
[20, 45, 12, 36]
[20, 45, 'rose', 36]
List Parameters
A list can also be passed as a parameter to a function.
If changes are done, then it is notified to main program.
The list arguments are always passed by reference only.
Program:
def delete(list1):
del list1[3]
return list1
list1=[20,30,12,56,23,100]
print('List Argument:',delete(list1))
Output:
List Argument: [20, 30, 12, 23, 100]
6
TUPLES
A tuple consists of number of values separated by commas and enclosed within
parentheses.
Tuples are similar to lists.
Tuples are immutable sequences. The elements in the tuple cannot be modified.
The difference between tuple and lists are the tuple cannot be modified like lists and
tuples use parentheses, whereas list use square brackets.
Program:
#Tuple Creation
t1=(23,56,12,20,67,'rose','grapes')
t2='r','g','j','s','f'
empty=()
single=(22,)#Single element tuple
nested=(67,89,t1,t2)#nested tuple
print(t1)
print(t2)
print(empty)
print(single)
print(nested)
Output:
(23, 56, 12, 20, 67, 'rose', 'grapes')
('r', 'g', 'j', 's', 'f')
()
(22,)
(67, 89, (23, 56, 12, 20, 67, 'rose', 'grapes'), ('r', 'g', 'j', 's', 'f'))
TUPLE OPERATIONS
Concatenation (+) – -> Combine two tuples
t1=('a','b','c')
7
t2=('d','e','f')
print(t1+t2)
Output:
('a', 'b', 'c', 'd', 'e', 'f')
Repeat (*) - Repeat tuples given number of times.
t1=('c','d')
Output
('c', 'd', 'c', 'd', 'c', 'd')
Membership Operator (in)
t=('a','c','f','g','h','x')
print('c' in t)
Ouput:
True
Inverse(not in)
print('z' not in t)
Output:
True
Python Tuple Methods
my_tuple = ('a','p','p','l','e')
print(my_tuple.count('p'))
print (my_tuple.index('l'))
Output:
2
3
Built-in Functions with Tuple
len()
Return the length (the number of items) in the tuple.
max()
Return the largest item in the tuple.
min()
Return the smallest item in the tuple
sorted()
Take elements in the tuple and return a new sorted list (does not sort the tuple itself).
sum()
Retrun the sum of all elements in the tuple.
tuple()
Convert an iterable (list, string, set, dictionary) to a tuple.
Program
t=(4,6,1,3,9,5,8)
print(len(t))
print(max(t))
print(min(t))
print(sorted(t))
print(sum(t))
print(tuple('welcome'))
8
Output:
7
9
1
[1, 3, 4, 5, 6, 8, 9]
36
('w', 'e', 'l', 'c', 'o', 'm', 'e')
DICTIONARY:
It is a collection of pair or elements.
Each pair contains key & value.
Key and value are separated using : symbol.
Each pair is separated using , symbol.
The whole dictionary is enclosed using {}.
Keys are immutable & values are mutable.
Ex:
d1={1:'fruit',2:'vegetables',3:'cereals'}
print(d1)
o/p:
{1: 'fruit', 2: 'vegetables', 3: 'cereals'}
OPERATIONS:
1. Create - Creating a new dictionary
2. Delete - Removing an element
3. Update –Adding a new element
4. Accessing – Displaying the elements
Program
a={}
a[1]='red'
a[2]='blue'
a[3]='green'
a[4]='grey'
print("Creating a new dictionary")
print(a)
del a[3]
print("After deletion")
print(a)
print("Accessing elements")
print(a[2])
print("Updating Dictionary")
a[1]='orange'
print(a)
Output
Creating a new dictionary
{1: 'red', 2: 'blue', 3: 'green', 4: 'grey'}
After deletion
{1: 'red', 2: 'blue', 4: 'grey'}
Accessing elements
blue
Updating Dictionary
9
{1: 'orange', 2: 'blue', 4: 'grey'}
Dictionary Methods:
Program:
h1={1:'APPLE',2:'GRAPES',3:'GUAVA'}
temp=h1.copy()
print("copy()=",temp)
print("items()=",h1.items())
print("keys()=",h1.keys())
print("pop()=",h1.pop(1))
print("popitem()=",h1.popitem())
h1.clear()
print("clear()=",h1)
Output:
copy()= {1: 'APPLE', 2: 'GRAPES', 3: 'GUAVA'}
items()= dict_items([(1, 'APPLE'), (2, 'GRAPES'), (3, 'GUAVA')])
keys()= dict_keys([1, 2, 3])
pop()= APPLE
popitem()= (3, 'GUAVA')
clear()= {}
Illustrative Problems:
10