2. List and Dictionary in Python (Syllabus)
Lists: list operations - creating, initializing, traversing and
manipulating lists, list methods and built-in functions.
len(), list(), append(), extend(), insert(), count(), index()
remove(), pop(), reverse(), sort(), sorted(), min(), max(), sum()
Dictionary: concept of key-value pair, creating, initializing,
traversing, updating and deleting elements, dictionary methods
and built-in functions.
len(), dict(), keys(), values(), items(), get(), update(), clear(),
del()
1
Sangita Panchal
3. • A list is a sequence of comma separated values (elements/objects) enclosed
in square brackets [].
• The values in a list may be of different types (integer, float, string, list, tuple
etc.) – Heterogeneous data type.
• Lists are mutable i.e. values in a list can be edited /changed.
Sangita Panchal
List – Creating and Initializing list
L1 = [] #Empty list
L1 = [‘English’, 45, ‘Maths’, 86, ‘Rajesh’, 1234]
L2 = [12, 15, ‘Manish’, [45, 87], 23] #Nested List
L3 = [‘Sonia’, (‘E001’, ‘D001’), 34000] # Tuple within a list
L = [1,"abc",(23,12),[23,"str"],{1:"A",2:"B"}]
# number, string, tuple, list, dict
2
4. List items can be accessed by using their index or indices
Sangita Panchal
Accessing List by Index
Forward
Index
Backward
Index
L = ["Eng",65,"Maths",97, "Sc.",89]
print(L[3])
print(L[1+4])
print(L[2*2])
print(L[5-4+1])
97
89
Sc.
Maths
3
5. Slicing
[ start index : end index : step ]
The default of start index is 0, step is 1. It will display data from
start index to end-1 index.
Sangita Panchal
Accessing List - Slicing
L = ["Eng",65,"Maths",97, "Sc.",89]
print(L[ :4])
print(L[2: ])
print(L[ : ])
print(L[ : :-1])
['Eng', 65, 'Maths', 97]
['Maths', 97, 'Sc.', 89]
['Eng', 65, 'Maths', 97, 'Sc.', 89]
[89, 'Sc.', 97, 'Maths', 65, 'Eng']
4
6. Sangita Panchal
Change data in the list
L = ["Eng",65,"Maths",97, "Sc.",89]
print(L)
L[1] = 90
print(L)
L[2:4] = ['IP',99]
print(L)
L[1:3] = [ ]
print(L)
['Eng’, 65, 'Maths', 97, 'Sc.', 89]
['Eng', 90, 'Maths', 97, 'Sc.', 89]
['Eng', 90, 'IP', 99, 'Sc.', 89]
['Eng', 99, 'Sc.', 89]
5
7. Sangita Panchal
List operations – Concatenation
A = [12, 43]
B = [34, 78]
C = A + B
print("C = ",C)
A = A + B
print("A = ",A)
B += A
print("B = ",B)
C = [12, 43, 34, 78]
A = [12, 43, 34, 78]
B = [34, 78, 12, 43, 34, 78]
A = [12, 43]
A = A + 5
TypeError: can only
concatenate list (not "int")
to list
Concatenation: It takes ‘+’ operator to concatenate with another list.
6
Correct
A = [12,43]
A = A + [5]
8. Sangita Panchal
List operations – Repetition
L = [12, 43]
print(L * 2)
L1 = [1,"Amit"]
print(3 * L1)
[12, 43, 12, 43]
[1, 'Amit', 1, 'Amit', 1, 'Amit']]
L = [12, 43]
L2 = [3]
print(L * L2)
TypeError: can't multiply
sequence by non-int value
Repetition: It takes ‘*’ operator to repeat the list content by the
given number.
7
9. Sangita Panchal
List operations –Membership
L = [12, 43]
L1 = [1,"Amit"]
print("Amit" in L1)
print(12 not in L)
True
False
Membership: It check whether the given element is present in
the list or not. It uses
in : The given element is present.
not in: The given element is not present.
8
10. Sangita Panchal
Traversing a List
L = [12,"Amit",[23,43,29]]
for i in L:
print(i, end = " ")
print()
for i in range(len(L)):
print(L[i],end = " ")
12 Amit [23, 43, 29]
12 Amit [23, 43, 29]
9
There are two ways to traverse the list.
1. Element / Member
2. Index – 0, 1, …len(L) - 1
11. Sangita Panchal
Traversing a List – To add number five to each element in
the list.
L = [12, 43, 17, 34, 29]
print("Initial list is: ", L)
print("After adding 5: ", end = "")
for i in range(len(L)):
L[i] += 5
print(L)
Initial list is: [12, 43, 17, 34, 29]
After adding 5: [17, 48, 22, 39, 34]
10
12. Sangita Panchal
List methods – len(), append(), extend()
L = [14,32,29]
L1 = [22,25]
print(L,len(L))
L.append(L1)
print(“After append”,L,len(L))
L = [14,32,29]
print(L,len(L))
L1 = [22,25]
L.extend(L1)
print(“After extend”,L,len(L))
[14, 32, 29] 3
After append [14, 32, 29, [22, 25]] 4
[14, 32, 29] 3
After extend [14, 32, 29, 22, 25] 5
11
append(): It adds the object as one element.
extend(): It adds the elements in the object as
individual element in the list.
13. Sangita Panchal
List methods – count(),insert(),remove()
L = [14,32,29,28,32,14,28]
print(L)
print("Count of 14: ",L.count(14))
L.insert(3,14)
print(L)
print("Count of 14: ",L.count(14))
L.remove(14)
L.remove(14)
print(L)
print("Count of 14: ",L.count(14))
[14, 32, 29, 28, 32, 14, 28]
Count of 14: 2
[14, 32, 29, 14, 28, 32, 14, 28]
Count of 14: 3
[32, 29, 28, 32, 14, 28]
Count of 14
12
count(): It counts the given data present in the list.
insert(): It inserts the data at a given location in the list.
remove(): It removes the given data in a list, whichever comes first from the left to right.
14. Sangita Panchal
List methods – reverse(), sort()
L = [14,32,29,28,12,24]
print(L)
L.reverse()
print("List in reverse order:",L)
L.sort()
print("List in ascending order:",L)
L.sort(reverse = True)
print("List in descending order:",L)
[14, 32, 29, 28, 12, 24]
List in reverse order:
[24, 12, 28, 29, 32, 14]
List in ascending order:
[12, 14, 24, 28, 29, 32]
List in descending order:
[32, 29, 28, 24, 14, 12]
reverse(): it reverses the member in the list.
sort(): It sorts the data in the list in ascending order.
sort(reverse = True): it sorts the data in the list in descending order.
Note: In sort(), it works with homogeneous data type.
13
15. Sangita Panchal
List methods – sort() in string data type
L = ["Zen","Ben","Arif","Kity"]
print("Original list", L,sep = ‘n’)
L.sort()
print("List in Ascending order",L,sep = ‘n’)
L.sort(reverse = True)
print("List in Descending order",L,sep = ‘n’)
Original list
['Zen', 'Ben', 'Arif', 'Kity']
List in Ascending order
['Arif', 'Ben', 'Kity', 'Zen']
List in Descending order
['Zen', 'Kity', 'Ben', 'Arif']
14
16. Sangita Panchal
List methods – sort() in nested list
L = [[23,12],[34,45],[22,11]]
print("Original list", L,sep = ‘n’))
L.sort()
print("List in Ascending order",L,sep = ‘n’)
L.sort(reverse = True)
print("List in Descending order",L,sep = ‘n’))
Original list
[[23, 12], [34, 45], [22, 11]]
List in Ascending order
[[22, 11], [23, 12], [34, 45]]
List in Descending order
[[34, 45], [23, 12], [22, 11]]
15
17. Sangita Panchal
List methods – sort() vs sorted
L = [12,9,5,2,3]
print("Original list", L)
L1 = sorted(L)
print("List in Ascending order",L1)
L1 = sorted(L,reverse = True)
print("List in Descending order",L1)
Original list [12, 9, 5, 2, 3]
List in Ascending order [2, 3, 5, 9, 12]
List in Descending order [12, 9, 5, 3, 2]
16
18. Sangita Panchal
List methods – sort() vs sorted
L = ["Zen","Ben","Arif","Kity"]
print("Original list", L, sep = ‘n’)
L1 = sorted(L)
print("List in Ascending order",L1,sep = ‘n’)
L1 = sorted(L,reverse = True)
print("List in Descending order",L1,sep = ‘n’)
17
Original list
['Zen', 'Ben', 'Arif', 'Kity']
List in Ascending order
['Arif', 'Ben', 'Kity', 'Zen']
List in Descending order
['Zen', 'Kity', 'Ben', 'Arif']
19. Sangita Panchal
List methods – pop(), del
L = [14,32,29,28,12,24]
print(L)
print("Remove the -1 index value:“)
L.pop() ; print(L)
print("Remove the 2 index value:“)
L.pop(2) ; print(L)
print("Remove the 1 index value:“
del L[1] ; print(L)
print("Delete the entire list")
del L ; print(L)
[14, 32, 29, 28, 12, 24]
Remove the -1 index value:
24
[14, 32, 29, 28, 12]
Remove the 2 index value:
29
[14, 32, 28, 12]
Remove the 1 index value:
[14, 28, 12]
Delete the entire list
NameError: name 'L' is not defined12]
18
pop(): It deletes the element mentioned as index. The default index is -1.
del : It deletes the element mentioned as index, otherwise it deletes the entire list
permanently.
20. Sangita Panchal
List methods – index()
L = [14,32,29,32,12,24]
print(L)
print("Index of 32 from left",end ="")
print(L.index(32))
print("Index of 32 after index 2",end ="")
print(L.index(32,2))
print("Index of 40 not present",end ="")
print(L.index(40))
[14, 32, 29, 32, 12, 24]
Index of 32 from left 1
Index of 32 after index 2 3
Index of 40 not present
ValueError: 40 is not in list
19
21. Sangita Panchal
List built-in functions – min(),max(),sum()
L = [14,32,29,32,12,24]
print(L)
print("Maximum:",max(L))
print("Minimum:",min(L))
print("Sum:",sum(L))
print("Average:",round(sum(L)/len(L),2))
[14, 32, 29, 32, 12, 24]
Maximum: 32
Minimum: 12
Sum: 143
Average: 23.83
20
max(): It returns the maximum value in the list.
min(): it returns the minimum value in the list.
sum(): it returns the sum of all the values in the list.
Note: min(), max() works with number or string data type.
sum() works with number data type only.
22. Sangita Panchal
Program 1: To input how many marks, enter marks and
display the average mark.
n = int(input("Enter no. of marks"))
L = []
for i in range(n):
marks = int(input("Enter marks"))
L.append(marks)
s = 0
for i in L:
s += i
print("Average mark", s/n)
Enter no. of marks5
Enter marks23
Enter marks19
Enter marks22
Enter marks15
Enter marks20
Average mark 19.8
21
23. Sangita Panchal
Program 2: To input number of marks, enter marks, search whether
the given mark is present at location or not.
L = []
n = int(input("How many numbers"))
for i in range(n):
n = int(input("Enter number"))
L.append(n)
num = int(input("Enter the number
to be searched: "))
pos = -1
for i in range(n):
if L[i] == num: pos = i ; break
if pos == -1 : print("Number",num,"is not present")
else: print("Number",num,"is present at",pos, "position")
How many numbers5
Enter number21
Enter number23
Enter number20
Enter number17
Enter number19
Enter the number to be searched: 20
Number 20 is present at 2 position
22
24. Sangita Panchal
Program 3: A menu driven program of list, to do the following:
1. Add a data
2. Insert a data
3. Add list
4. Modify data by index
5. Delete by value
6. Delete by position
7. Sort in ascending order
8. Sort in descending order
9. display list
23
25. Sangita Panchal
L = []
while True:
print("""1 append, 2 insert, 3 append list,
4 - modify, 5 - Delete by position,
6 - Delete by value, 7 - sort in ascending
8 - Sort in descending, 9- Display""")
choice = int(input("Enter the choice"))
if choice == 1:
n = int(input("Enter data"))
L.append(n) ; print(L)
elif choice == 2:
n = int(input("Enter data"))
pos = int(input("Enter position"))
L.insert(pos,n) ; print(L)
elif choice == 3:
nList = eval(input("Enter the list to be appended: "))
L.extend(nList) ; print(L)
24
26. Sangita Panchal
elif choice == 4:
i = int(input("Enter the data position to modified: "))
if i < len(L):
num = eval(input("Enter the new element: "))
L[i] = num
else:
print("Position not in the list")
print(L)
elif choice == 5:
i = int(input("Enter the element position to be deleted: "))
if i < len(L):
num = L.pop(i)
else:
print("nPosition not in the list")
print(L)
25
27. Sangita Panchal
elif choice == 6:
num = int(input("nEnter the element to be deleted: "))
if num in L:
L.remove(num)
else:
print("nElement",element,"is not present in the list")
elif choice == 7:
L.sort()
elif choice == 8:
L.sort(reverse = True)
elif choice == 9:
print("nThe list is:", L)
else:
print("Exit")
break
26
28. Sangita Panchal
1 append, 2 insert, 3 append list,
4 - modify, 5 - Delete by position,
6 - Delete by value, 7 - sort in ascending
8 - Sort in descending, 9- Display
Enter the choice1
Enter data18
[18]
1 append, 2 insert, 3 append list,
4 - modify, 5 - Delete by position,
6 - Delete by value, 7 - sort in ascending
8 - Sort in descending, 9- Display
Enter the choice2
Enter data23
Enter position0
[23, 18]
1 append, 2 insert, 3 append list,
4 - modify, 5 - Delete by position,
6 - Delete by value, 7 - sort in ascending
Enter the choice3
Enter the list to be appended: 25,21,20
[23, 18, 25, 21, 20]
1 append, 2 insert, 3 append list,
4 - modify, 5 - Delete by position,
6 - Delete by value, 7 - sort in ascending
8 - Sort in descending, 9- Display
Enter the choice4
Enter the data position to modified: 2
Enter the new element: 15
[23, 18, 15, 21, 20]
1 append, 2 insert, 3 append list,
4 - modify, 5 - Delete by position,
6 - Delete by value, 7 - sort in ascending
8 - Sort in descending, 9- Display
Enter the choice5
Enter the element position to be deleted: 1
[23, 15, 21, 20]
27
29. Sangita Panchal
28
1 append, 2 insert, 3 append list,
4 - modify, 5 - Delete by position,
6 - Delete by value, 7 - sort in ascending
8 - Sort in descending, 9- Display
Enter the choice6
Enter the element to be deleted: 21
[23, 15, 20]
1 append, 2 insert, 3 append list,
4 - modify, 5 - Delete by position,
6 - Delete by value, 7 - sort in ascending
8 - Sort in descending, 9- Display
Enter the choice7
[15, 20, 23]
1 append, 2 insert, 3 append list,
4 - modify, 5 - Delete by position,
6 - Delete by value, 7 - sort in ascending
8 - Sort in descending, 9- Display
Enter the choice8
[23, 20, 15]
1 append, 2 insert, 3 append list,
4 - modify, 5 - Delete by position,
6 - Delete by value, 7 - sort in ascending
8 - Sort in descending, 9- Display
Enter the choice9
The list is: [23, 20, 15]
1 append, 2 insert, 3 append list,
4 - modify, 5 - Delete by position,
6 - Delete by value, 7 - sort in ascending
8 - Sort in descending, 9- Display
Enter the choice10
Exit
31. Sangita Panchal
Dictionary in Python
A dictionary is a mutable object that can store any number of Python
objects. It falls under mapping – a mapping between a set of keys
with corresponding values.
The items are separated by comma and the entire dictionary is
enclosed in curly braces.
Each item consists of two parts – key and a value, separated by a
colon (:).
Keys are unique in dictionary. They must be of an immutable data
types such as strings, numbers or tuples.
The values may have duplicate values. They can be of any data
type.
30
33. Sangita Panchal
Creating an Empty Dictionary
D = {}
print("D = ",D)
D1 = dict()
print("D1 = ",D1)
Two ways to create an empty dictionary
D = {}
D1 = {}
32
34. Sangita Panchal
Accessing Items in a Dictionary
D = {'Amit':56,'Joe':32}
print(D)
print("The value of Joe:",D['Joe'])
print("The value of Amit:" D['Amit'])
The items of the dictionary are accessed via the keys rather than
the index. Each key treated as an index and map with the value.
{'Amit': 56, 'Joe': 32}
The value of Joe: 32
The value of Amit: 56
33
35. Sangita Panchal
Membership operation in a Dictionary
D = {'Amit':56,'Joe':32}
print(D)
print("Check for Amit:",'Amit' in D)
print("Check for Seema:",'Seema' in D)
print("Check of Joe not present",'Joe' not in D)
The membership operator (in) checks whether the key is present in
a dictionary or not. It returns True or False.
{'Amit': 56, 'Joe': 32}
Check for Amit: True
Check for Seema: False
Check of Joe not present False
34
36. Sangita Panchal
Adding /Modifying the item in a Dictionary
D = {'Amit':56,'Joe':32}
print(D)
D['Amit'] = 100
D['Seema'] = 78
print("The updated dictionary")
print(D)
As dictionary is mutable, you can add an item or modify the value
of an already existing key in a dictionary.
{'Amit': 56, 'Joe': 32}
The updated dictionary
{'Amit': 100, 'Joe': 32, 'Seema': 78}
35
37. Sangita Panchal
Traversing a Dictionary
D = {'Amit':56,'Joe':32,'Sid':45}
for key in D:
print(key,":",D[key])
You can traverse a dictionary using for loop. There are two ways to
do the traversing.
Amit : 56
Joe : 32
Sid : 45
D = {'Amit':56,'Joe':32,'Sid':45}
for key,value in D.items():
print(key,":",value)
Amit : 56
Joe : 32
Sid : 45
36
38. Sangita Panchal
Built-in functions and methods in Dictionary – len(), update()
D = dict() ; print(D,len(D))
D1 = {'Amit':56,'Joe':32,'Sid':45}
D.update(D1)
print(D,len(D))
D2 = {'Joe':43,'Jia':47}
D.update(D2) ; print(D,len(D))
{} 0
{'Amit': 56, 'Joe': 32, 'Sid': 45} 3
{'Amit': 56, 'Joe': 43, 'Sid': 45, 'Jia': 47} 4
dict(): It creates and empty dictionary.
len(): It returns the number of items in the dictionary.
update(): If key is present, it updates the value, otherwise, adds the
item in the dictionary.
37
39. Sangita Panchal
Built-in functions and methods in Dictionary –
keys(),values(),items()
D = {'Amit':56,'Joe':32,'Sid':45,'Jia':47}
print(D.keys())
print(D.values())
print(D.items())
dict_keys(['Amit', 'Joe', 'Sid', 'Jia'])
dict_values([56, 32, 45, 47])
dict_items([('Amit', 56), ('Joe', 32), ('Sid', 45), ('Jia', 47)])
keys(): It returns the list of keys in the dictionary.
values(): it returns the list of values in the dictionary.
items(): It returns the key, value pair in tuple and entire data in list.
38
40. Sangita Panchal
Built-in functions and methods in Dictionary – get()
D = {'Amit':56,'Joe':32,'Sid':45,'Jia':47}
D = {'Amit':56,'Joe':32,'Sid':45}
print(D.get('Sid'))
print(D.get('amit'))
print(D['Sid'])
print(D['amit'])
45
None
45
KeyError: 'amit'
It returns the value corresponding to the passed key, if present;
otherwise it returns None. It is similar to D[key].
39
41. Sangita Panchal
Built-in functions and methods in Dictionary – get()
D = {'Amit':56,'Joe':32,'Sid':45}
del D['Joe']
print(“Aafter deleting Joe“, D)
D.clear()
print(“After deleting content“,D)
del D
print("Permanently deletes the
dictionary“,D)
After deleting Joe {'Amit': 56, 'Sid': 45}
After deleting content {}
Permanently deletes the dictionary
NameError: name 'D' is not defined'
clear(): deletes the entire content leaving empty dict.
del: deletes the specified item or entire dict permanently.
40
42. Sangita Panchal
Write a python program to create a dictionary from a string.
Sample string ‘w3resource’
Expected output {‘3’:1, ‘s’:1, ‘r’:2, ‘u’:1, ‘w’:1, ‘c’:1, ‘e’:2, ‘o’:1}
st = input("Enter a string ")
d = {}
for ch in st:
if ch in d:
d[ch] += 1
else:
d[ch] = 1
print(d)
Enter a string AEOBCAB
{'A': 2, 'E': 1, 'O': 1, 'B': 2, 'C': 1}
41
43. Sangita Panchal
Write a program to convert a number entered by the user into its
corresponding number in words. For example, if the number is 876,
then the output should be ‘Eight Seven Six’
num = input("Enter any number")
d = {0: 'Zero', 1:'One', 2:'Two', 3:'Three', 4:'Four',
5:'Five', 6:'Six', 7:'Seven', 8: 'Eight', 9:'Nine'}
result = ''
for ch in num:
key = int(ch)
value = d[key]
result = result + " " +value
print( result)
Enter any number17439
One Seven Four Three Nine
42
44. Sangita Panchal
Write a program to input your friend’s names and their phone
numbers and store them in the dictionary as the key-value pair.
Perform the following operations on the dictionary:
Display the name and phone number for all your friends.
Add a new key-value pair in this dictionary and display the
modified dictionary.
Enter the name whose phone number you want to modify. Display
the modified dictionary.
Enter the friend’s name and check if a friend is present in the
dictionary or not.
Display the dictionary in sorted order of names.
43
45. Sangita Panchal
D = {}
while True:
print("1 create/add, 2 modify, 3 search, 4 sort, 5 exit")
choice = int(input("Enter choice"))
if choice == 1:
while True:
name = input("Enter your name ")
phone = input("Enter your phone number")
D[name] = phone
choice = input("Continue Y/N")
if choice.upper() == "N":
break
print(D)
44
46. Sangita Panchal
elif choice == 2:
n = input("Enter the name whose phone number
you want to modified")
flag = 0
for i in D.keys():
if i == n:
p = input("Enter the modified phone number")
D[i] = p ; flag = 1 ; break
if flag == 0: print("Name not found")
print("The dictionary is = ", D)
45
47. Sangita Panchal
elif choice == 3:
n = input("Name")
flag = 0
for i in D.keys():
if i == n: print("Present") ; flag = 1 ; break
if flag == 0: print("Name Not present")
elif choice == 4:
for key,value in sorted(D.items()):
print(key,":",value,end = ",")
elif choice == 5: print("End of program");break
else: print("Enter correct choice")
46
48. Sangita Panchal
47
1 create/add, 2 modify, 3 search, 4 sort, 5 exit
Enter choice1
Enter your name samy
Enter your phone number2134
Continue Y/Ny
Enter your name joe
Enter your phone number4343
Continue Y/Nn
{'samy': '2134', 'joe': '4343'}
1 create/add, 2 modify, 3 search, 4 sort, 5 exit
Enter choice2
Enter the name whose phone number you want to modifiedjoe
Enter the modified phone number1111
The dictionary is = {'samy': '2134', 'joe': '1111'}
1 create/add, 2 modify, 3 search, 4 sort, 5 exit
Enter choice3
Namesamy
Present
1 create/add, 2 modify, 3 search, 4 sort, 5 exit
Enter choice4
joe : 1111,samy : 2134,1 create/add, 2 modify, 3 search, 4 sort, 5 exit
Enter choice5
End of program