You are on page 1of 2

UNIT IV LISTS, TUPLES, DICTIONARIES

1. Lists: List is a collection of sequence elements between square brackets [ ] Example: list=[1,2,3,4]
Adv: Lists are mutable (can change the value) and Lists can be heterogeneous (different) datatype

2. List operations: List respond to the + and * operators much like strings, they mean concatenation & repetition
• Finding the length len( ) Eg: list1=[1,2,3,4]; print(len(list1)) output: 4
• Concatenation + Eg: list1=[1,2,3,4]; list2=[5,6,7,8]; print(list1+list2) output: [1,2,3,4,5,6,7,8]
• Repetition * Eg: list1=[1,2,3,4]; print(list1 * 2) output: [1,2,3,4] [1,2,3,4]
• Membership in not in Eg: list1=[1,2,3,4]; print(2 in (list1)) output: True
• Iteration loop Eg: list1=[1,2,3,4];
for x in list1:
print(x) output: 1 2 3 4
3. List slices: We can access a range of items in a list by using slicing operator (colon) :
Eg: list1=[1,2,3,4]; print(list1[1:3]); print(list1[2:]); print(list1[:2]); print(list1[:]) output: [2,3] [3,4] [1,2] [1,2,3,4]

4. List methods: Lot of inbuilt methods that are available with list object. They are accessed as list.method( )
append( ) - Add an element to the end of the list Program Output
extend( ) - Add all elements of a list to the another list list1=[1,2,3,4]; list2=[7] [1, 2, 3, 4, 5]
insert( ) - Insert an item at the defined location list1.append(5); print(list1) [1, 2, 3, 4, 5, 7]
remove( ) - Removes an item from the list list1.extend(list2);print(list1) [10, 1, 2, 3, 4, 5, 7]
pop( ) - Removes and returns an element at the given location list1.insert(0,10); print(list1) [10, 1, 2, 3, 4, 7]
index( ) - Returns the location of the first matched item list1.remove(5); print(list1) [10, 1, 2, 3, 4]
list1.pop(); print(list1) 1
count( ) - Returns the count of number of items passed as an argument print(list1.count(1)) [1, 2, 3, 4, 10]
sort( ) - Arranging the elements in an ascending order list1.sort(); print(list1) [10, 4, 3, 2, 1]
reverse( ) - Reverse the order of items in the list list1.reverse(); print(list1)
copy( ) - Returns the shallow copy of the list
clear( ) - Remove all items from the list
5. List loop: Using range ( ) function returns an immutable sequence object of integers between start and stop integer
Program Output
a=[1,2,3,4,5,6,7,8,9,10] [1,2,3,4,5,6,7,8,9,10] – without using range to print all values in the list
for i in a: 0 1 2 – stop value
print i 1 2 3 – start and stop value
for i in range(3): 0 2 4 6 8 – start, stop and step value
print i
for i in range(1,4):
print i
for i in range(0,10,2):
print i

6. Mutability: List is Mutable (Can change the value in the list). So you can access, update and delete the values easily.
Using slice operator [ : ] to change more values in the list
Program Output
list=[1,2,3,4,5]; print(list[0]) #Access single value 1
print(list); print(list[1:4]) #Access more value [1, 2, 3, 4, 5]
list[0]=10; print(list) #update single value [2, 3, 4]
list.append(100); print(list) #update single value using method [10, 2, 3, 4, 5]
list[1:3]=[12,14]; print(list) #update more value [10, 2, 3, 4, 5, 100]
del list[0]; print(list) #delete single value [10, 12, 14, 4, 5, 100]
del list[1:3]; print(list) # delete more value [12, 14, 4, 5, 100]
[12, 5, 100]

7. Aliasing: Multiple variables that contain references to the same object. The copy affects the original.
Eg: list1=[1,2,3,4,5]; list2=list1; print(list1,list2); list2[0]=150; print(list1,list2);
Output: ([1, 2, 3, 4, 5], [1, 2, 3, 4, 5])
([150, 2, 3, 4, 5], [150, 2, 3, 4, 5])
8. Cloning: To create a new object that has the same value as an existing object. But the copy does not affect the original
Eg: list1=[1,2,3,4,5]; list2=list1[ : ]; print(list1,list2); list2[0]=150; print(list1,list2);
Output: ([1, 2, 3, 4, 5], [1, 2, 3, 4, 5]) Program Output
([1, 2, 3, 4, 5], [150, 2, 3, 4, 5]) def listaspara(a): 15
9. List as parameters: sum=0
for i in a:
• An entire list can be transferred to a function as a parameter. sum=sum+i
• Passing a list as an argument actually passes a reference to print(sum)
the list, not a copy or clone of the list. a=[1,2,3,4,5]
listaspara(a)
10. Tuples: A tuple is a sequence of immutable python object. - (Tuple elements does not change after assignment)
Tuple is full of heterogeneous data structure, the elements between parenthesis ( ) Example: tuple=(1,’a’,2.5)
Adv: Some tuples can be used as dictionary keys. Tuples make your code safer – “Write protect”
Example: tuple=(1,2,3,4,5); tuple=(“Physics”,199,”Chemistry”,197,”Python”,200)
Tuple=(“matrix”,[1,2,3],(4,5,6)) # List inside tuple
11. Tuple assignment: Without using temporary variable to swap the values between variables is possible in tuple.
Example: x=2; y=3; print(x,y) Output:
x,y=y,x #tuple assignment without temporary variable 23
print(x,y) 32
12. Tuple as return value: import math Output
Function can always only return a single value, def circlestats(r): (62.83185307179586,
but if the value is a tuple, the effect is circumference=2*math.pi*r 314.1592653589793)
the same as returning multiple values. area=math.pi*r*r
return(circumference,area)
result=circlestats(10)
print(result)
13. Tuple operations: Tuple respond to the + and * operators much like strings, they mean concatenation & repetition
• Finding the length len( ) Eg: tuple1=(1,2,3,4); print(len(tuple1)) output: 4
• Concatenation + Eg: tuple1=(1,2,3,4); tuple2=(5); print(tuple1+tuple2) output: (1,2,3,4,5)
• Repetition * Eg: tuple1=(1,2,3,4); print(tuple1 * 2) output: (1,2,3,4) (1,2,3,4)
• Membership in not in Eg: tuple1=(1,2,3,4); print(2 in (tuple1)) output: True
• Iteration loop Eg: tuple1=(1,2,3,4); for x in tuple1: print(x) output: 1 2 3 4
14. Tuple Built in methods/functions
Function Description Example Output
all( ) Returns true if all elements of the tuple are true print(all(1,2,3)) True
any( ) Returns true if any element of the tuple is true print(any(1,2,0)) True
len( ) Returns the length of the tuple print(len(1,2,3)) 3
max( ) Returns the largest item in the tuple print(max(1,2,3)) 3
min( ) Returns the smallest item in the tuple print(min(1,2,3)) 1
sum( ) Returns the sum of all elements in the tuple print(sum(1,2,3)) 6
15. Dictionaries: It is an unordered collection of items. The items are in the form of { key:value } pairs.
Creating dictionary is placing items inside curly braces { } separated by comma. Key separeated by :
Example: dict={‘carname’:’benz’, ‘class’:’s1’, ‘price’:5000000}
Properties of Dictionary key:1.More than one entry per key not allowed 2.Key must be immutable, values may be mutable
16. Operations and Methods
Operations & Description Program Output
Methods
dict( ) Creating empty dictionary m=dict( ); print(m) { }
del( ) del statement removes a key:value del dict['class']; print(dict) {‘carname’:’benz’,
pairs ‘price’:5000000}
len( ) To find the length of the dictionary print(len(dict)) 2
pop( ) To delete the key from the dictionary dict.pop('carname'); print(dict) {‘price’:5000000}
popitem( ) To delete the top of item in the dict.popitem( ) { }
dictionary
keys( ) Returns list of keys in the dictionary dict={ 'carname': 'benz ', 'class': [‘carname’,’class’,’price’]
's1 ', 'price ':5000000}
print(dict.keys( ))
values( ) Returns list of values in the print(dict.values( )) [‘benz’,’s1’,5000000]
dictionary
items( ) Returns a list of all items in dictionary print(dict.items( )) [‘carname’:’benz’, ‘class’:’s1’,
‘price’:5000000]
update( ) Adds dictionary dict2; key values pair dict2={ 'place ': 'canada '} {‘carname’:’benz’, ‘class’:’s1’,
to dict dict.update(dict2); print(dict) ‘price’:5000000,’place’,’canada’}
copy( ) Copy the items from one to another dict3=dict.copy(); Same as above
clear( ) It removes all the items in dictionary dict.clear( ); print(dict) {}
17. Advanced list processing - List comprehension: It expresses an entire loop in a single statement. So it is an elegant.
Program Output
pow=[ ] Enter upper limit 6
n=int(input(“Enter upper limit”) [1,2,4,8,16,32]
pow=[2**i for i in range(n)]
print(pow)

You might also like