SlideShare a Scribd company logo
LIST IN PYTHON
Mutable data type
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
• 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
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
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
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
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]
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
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
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
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
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.
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.
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
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
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
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
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']
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.
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
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.
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
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
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
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
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
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
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
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
DICTIONARY IN
PYTHON
Mutable data type
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
Sangita Panchal
Dictionary in Python
D1 = {'Ani': 12, 'John':32}
D2 = {('Mia', 45, 32): [56, 23, 23, 66, 77]}
D3 = {1:'Ginni', 2:'Anuj'}
D4 = { 1: ('Mrinal', 65), 2: ('Sia', 89)}
print(D1);print(D2)
print(D3);print(D4)
D5 = {[‘Ani’ , ’John’]: [12, 32 ]}
print(D5)
{'Ani': 12, 'John': 32}
{('Mia', 45, 32): [56, 23, 23, 66, 77]}
{1: 'Ginni', 2: 'Anuj'}
{1: ('Mrinal', 65), 2: ('Sia', 89)}
TypeError: unhashable type: 'list'
31
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
List and Dictionary in python

More Related Content

What's hot

Python tuple
Python   tuplePython   tuple
Python tuple
Mohammed Sikander
 
List , tuples, dictionaries and regular expressions in python
List , tuples, dictionaries and regular expressions in pythonList , tuples, dictionaries and regular expressions in python
List , tuples, dictionaries and regular expressions in python
channa basava
 
Python Dictionaries and Sets
Python Dictionaries and SetsPython Dictionaries and Sets
Python Dictionaries and Sets
Nicole Ryan
 
Python : Regular expressions
Python : Regular expressionsPython : Regular expressions
Python : Regular expressions
Emertxe Information Technologies Pvt Ltd
 
Linked List
Linked ListLinked List
Linked List
Ashim Lamichhane
 
Queue
QueueQueue
Data Structures in Python
Data Structures in PythonData Structures in Python
Data Structures in Python
Devashish Kumar
 
Python Modules
Python ModulesPython Modules
Python Modules
Nitin Reddy Katkam
 
2D Array
2D Array 2D Array
2D Array
Ehatsham Riaz
 
sorting and searching.pptx
sorting and searching.pptxsorting and searching.pptx
sorting and searching.pptx
ParagAhir1
 
Python Functions
Python   FunctionsPython   Functions
Python Functions
Mohammed Sikander
 
Arrays
ArraysArrays
Strings in Python
Strings in PythonStrings in Python
Strings in Python
Amisha Narsingani
 
Selection sorting
Selection sortingSelection sorting
Selection sorting
Himanshu Kesharwani
 
Python for loop
Python for loopPython for loop
Python for loop
Aishwarya Deshmukh
 
Introduction to Python
Introduction to Python  Introduction to Python
Introduction to Python
Mohammed Sikander
 
Python Flow Control
Python Flow ControlPython Flow Control
Python Flow Control
Mohammed Sikander
 
Python list
Python listPython list
Python list
Mohammed Sikander
 
Python Variable Types, List, Tuple, Dictionary
Python Variable Types, List, Tuple, DictionaryPython Variable Types, List, Tuple, Dictionary
Python Variable Types, List, Tuple, Dictionary
Soba Arjun
 
Unit 4 python -list methods
Unit 4   python -list methodsUnit 4   python -list methods
Unit 4 python -list methods
narmadhakin
 

What's hot (20)

Python tuple
Python   tuplePython   tuple
Python tuple
 
List , tuples, dictionaries and regular expressions in python
List , tuples, dictionaries and regular expressions in pythonList , tuples, dictionaries and regular expressions in python
List , tuples, dictionaries and regular expressions in python
 
Python Dictionaries and Sets
Python Dictionaries and SetsPython Dictionaries and Sets
Python Dictionaries and Sets
 
Python : Regular expressions
Python : Regular expressionsPython : Regular expressions
Python : Regular expressions
 
Linked List
Linked ListLinked List
Linked List
 
Queue
QueueQueue
Queue
 
Data Structures in Python
Data Structures in PythonData Structures in Python
Data Structures in Python
 
Python Modules
Python ModulesPython Modules
Python Modules
 
2D Array
2D Array 2D Array
2D Array
 
sorting and searching.pptx
sorting and searching.pptxsorting and searching.pptx
sorting and searching.pptx
 
Python Functions
Python   FunctionsPython   Functions
Python Functions
 
Arrays
ArraysArrays
Arrays
 
Strings in Python
Strings in PythonStrings in Python
Strings in Python
 
Selection sorting
Selection sortingSelection sorting
Selection sorting
 
Python for loop
Python for loopPython for loop
Python for loop
 
Introduction to Python
Introduction to Python  Introduction to Python
Introduction to Python
 
Python Flow Control
Python Flow ControlPython Flow Control
Python Flow Control
 
Python list
Python listPython list
Python list
 
Python Variable Types, List, Tuple, Dictionary
Python Variable Types, List, Tuple, DictionaryPython Variable Types, List, Tuple, Dictionary
Python Variable Types, List, Tuple, Dictionary
 
Unit 4 python -list methods
Unit 4   python -list methodsUnit 4   python -list methods
Unit 4 python -list methods
 

Similar to List and Dictionary in python

Data structures: linear lists
Data structures: linear listsData structures: linear lists
Data structures: linear lists
ToniyaP1
 
GE3151_PSPP_UNIT_4_Notes
GE3151_PSPP_UNIT_4_NotesGE3151_PSPP_UNIT_4_Notes
GE3151_PSPP_UNIT_4_Notes
Asst.prof M.Gokilavani
 
Python lists &amp; sets
Python lists &amp; setsPython lists &amp; sets
Python lists &amp; sets
Aswini Dharmaraj
 
Lecture2.pptx
Lecture2.pptxLecture2.pptx
Lecture2.pptx
Sakith1
 
Lecture-5.pdf
Lecture-5.pdfLecture-5.pdf
Lecture-5.pdf
Bhavya103897
 
Python Unit 5 Questions n Notes.pdf
Python Unit 5 Questions n Notes.pdfPython Unit 5 Questions n Notes.pdf
Python Unit 5 Questions n Notes.pdf
MCCMOTOR
 
python_avw - Unit-03.pdf
python_avw - Unit-03.pdfpython_avw - Unit-03.pdf
python_avw - Unit-03.pdf
AshaWankar1
 
STRING LIST TUPLE DICTIONARY FILE.pdf
STRING LIST TUPLE DICTIONARY FILE.pdfSTRING LIST TUPLE DICTIONARY FILE.pdf
STRING LIST TUPLE DICTIONARY FILE.pdf
omprakashmeena48
 
List_tuple_dictionary.pptx
List_tuple_dictionary.pptxList_tuple_dictionary.pptx
List_tuple_dictionary.pptx
ChandanVatsa2
 
Abstract Algebra and Category Theory
Abstract Algebra and Category Theory Abstract Algebra and Category Theory
Abstract Algebra and Category Theory
Naveenkumar Muguda
 
Session -5for students.pdf
Session -5for students.pdfSession -5for students.pdf
Session -5for students.pdf
priyanshusoni53
 
updated_list.pptx
updated_list.pptxupdated_list.pptx
updated_list.pptx
Koteswari Kasireddy
 
‏‏chap6 list tuples.pptx
‏‏chap6 list tuples.pptx‏‏chap6 list tuples.pptx
‏‏chap6 list tuples.pptx
RamiHarrathi1
 
Python Data Types.pdf
Python Data Types.pdfPython Data Types.pdf
Python Data Types.pdf
NehaSpillai1
 
Python Data Types (1).pdf
Python Data Types (1).pdfPython Data Types (1).pdf
Python Data Types (1).pdf
NehaSpillai1
 
Module-2.pptx
Module-2.pptxModule-2.pptx
Module-2.pptx
GaganRaj28
 
List Data Structure.docx
List Data Structure.docxList Data Structure.docx
List Data Structure.docx
manohar25689
 
Python lists
Python listsPython lists
Python lists
nuripatidar
 
Sixth session
Sixth sessionSixth session
Sixth session
AliMohammad155
 
02 Arrays And Memory Mapping
02 Arrays And Memory Mapping02 Arrays And Memory Mapping
02 Arrays And Memory MappingQundeel
 

Similar to List and Dictionary in python (20)

Data structures: linear lists
Data structures: linear listsData structures: linear lists
Data structures: linear lists
 
GE3151_PSPP_UNIT_4_Notes
GE3151_PSPP_UNIT_4_NotesGE3151_PSPP_UNIT_4_Notes
GE3151_PSPP_UNIT_4_Notes
 
Python lists &amp; sets
Python lists &amp; setsPython lists &amp; sets
Python lists &amp; sets
 
Lecture2.pptx
Lecture2.pptxLecture2.pptx
Lecture2.pptx
 
Lecture-5.pdf
Lecture-5.pdfLecture-5.pdf
Lecture-5.pdf
 
Python Unit 5 Questions n Notes.pdf
Python Unit 5 Questions n Notes.pdfPython Unit 5 Questions n Notes.pdf
Python Unit 5 Questions n Notes.pdf
 
python_avw - Unit-03.pdf
python_avw - Unit-03.pdfpython_avw - Unit-03.pdf
python_avw - Unit-03.pdf
 
STRING LIST TUPLE DICTIONARY FILE.pdf
STRING LIST TUPLE DICTIONARY FILE.pdfSTRING LIST TUPLE DICTIONARY FILE.pdf
STRING LIST TUPLE DICTIONARY FILE.pdf
 
List_tuple_dictionary.pptx
List_tuple_dictionary.pptxList_tuple_dictionary.pptx
List_tuple_dictionary.pptx
 
Abstract Algebra and Category Theory
Abstract Algebra and Category Theory Abstract Algebra and Category Theory
Abstract Algebra and Category Theory
 
Session -5for students.pdf
Session -5for students.pdfSession -5for students.pdf
Session -5for students.pdf
 
updated_list.pptx
updated_list.pptxupdated_list.pptx
updated_list.pptx
 
‏‏chap6 list tuples.pptx
‏‏chap6 list tuples.pptx‏‏chap6 list tuples.pptx
‏‏chap6 list tuples.pptx
 
Python Data Types.pdf
Python Data Types.pdfPython Data Types.pdf
Python Data Types.pdf
 
Python Data Types (1).pdf
Python Data Types (1).pdfPython Data Types (1).pdf
Python Data Types (1).pdf
 
Module-2.pptx
Module-2.pptxModule-2.pptx
Module-2.pptx
 
List Data Structure.docx
List Data Structure.docxList Data Structure.docx
List Data Structure.docx
 
Python lists
Python listsPython lists
Python lists
 
Sixth session
Sixth sessionSixth session
Sixth session
 
02 Arrays And Memory Mapping
02 Arrays And Memory Mapping02 Arrays And Memory Mapping
02 Arrays And Memory Mapping
 

Recently uploaded

CLASS 11 CBSE B.St Project AIDS TO TRADE - INSURANCE
CLASS 11 CBSE B.St Project AIDS TO TRADE - INSURANCECLASS 11 CBSE B.St Project AIDS TO TRADE - INSURANCE
CLASS 11 CBSE B.St Project AIDS TO TRADE - INSURANCE
BhavyaRajput3
 
TESDA TM1 REVIEWER FOR NATIONAL ASSESSMENT WRITTEN AND ORAL QUESTIONS WITH A...
TESDA TM1 REVIEWER  FOR NATIONAL ASSESSMENT WRITTEN AND ORAL QUESTIONS WITH A...TESDA TM1 REVIEWER  FOR NATIONAL ASSESSMENT WRITTEN AND ORAL QUESTIONS WITH A...
TESDA TM1 REVIEWER FOR NATIONAL ASSESSMENT WRITTEN AND ORAL QUESTIONS WITH A...
EugeneSaldivar
 
The Roman Empire A Historical Colossus.pdf
The Roman Empire A Historical Colossus.pdfThe Roman Empire A Historical Colossus.pdf
The Roman Empire A Historical Colossus.pdf
kaushalkr1407
 
The Art Pastor's Guide to Sabbath | Steve Thomason
The Art Pastor's Guide to Sabbath | Steve ThomasonThe Art Pastor's Guide to Sabbath | Steve Thomason
The Art Pastor's Guide to Sabbath | Steve Thomason
Steve Thomason
 
Phrasal Verbs.XXXXXXXXXXXXXXXXXXXXXXXXXX
Phrasal Verbs.XXXXXXXXXXXXXXXXXXXXXXXXXXPhrasal Verbs.XXXXXXXXXXXXXXXXXXXXXXXXXX
Phrasal Verbs.XXXXXXXXXXXXXXXXXXXXXXXXXX
MIRIAMSALINAS13
 
Instructions for Submissions thorugh G- Classroom.pptx
Instructions for Submissions thorugh G- Classroom.pptxInstructions for Submissions thorugh G- Classroom.pptx
Instructions for Submissions thorugh G- Classroom.pptx
Jheel Barad
 
The French Revolution Class 9 Study Material pdf free download
The French Revolution Class 9 Study Material pdf free downloadThe French Revolution Class 9 Study Material pdf free download
The French Revolution Class 9 Study Material pdf free download
Vivekanand Anglo Vedic Academy
 
Basic phrases for greeting and assisting costumers
Basic phrases for greeting and assisting costumersBasic phrases for greeting and assisting costumers
Basic phrases for greeting and assisting costumers
PedroFerreira53928
 
Fish and Chips - have they had their chips
Fish and Chips - have they had their chipsFish and Chips - have they had their chips
Fish and Chips - have they had their chips
GeoBlogs
 
Additional Benefits for Employee Website.pdf
Additional Benefits for Employee Website.pdfAdditional Benefits for Employee Website.pdf
Additional Benefits for Employee Website.pdf
joachimlavalley1
 
Unit 2- Research Aptitude (UGC NET Paper I).pdf
Unit 2- Research Aptitude (UGC NET Paper I).pdfUnit 2- Research Aptitude (UGC NET Paper I).pdf
Unit 2- Research Aptitude (UGC NET Paper I).pdf
Thiyagu K
 
Operation Blue Star - Saka Neela Tara
Operation Blue Star   -  Saka Neela TaraOperation Blue Star   -  Saka Neela Tara
Operation Blue Star - Saka Neela Tara
Balvir Singh
 
Digital Tools and AI for Teaching Learning and Research
Digital Tools and AI for Teaching Learning and ResearchDigital Tools and AI for Teaching Learning and Research
Digital Tools and AI for Teaching Learning and Research
Vikramjit Singh
 
How to Create Map Views in the Odoo 17 ERP
How to Create Map Views in the Odoo 17 ERPHow to Create Map Views in the Odoo 17 ERP
How to Create Map Views in the Odoo 17 ERP
Celine George
 
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
siemaillard
 
Thesis Statement for students diagnonsed withADHD.ppt
Thesis Statement for students diagnonsed withADHD.pptThesis Statement for students diagnonsed withADHD.ppt
Thesis Statement for students diagnonsed withADHD.ppt
EverAndrsGuerraGuerr
 
special B.ed 2nd year old paper_20240531.pdf
special B.ed 2nd year old paper_20240531.pdfspecial B.ed 2nd year old paper_20240531.pdf
special B.ed 2nd year old paper_20240531.pdf
Special education needs
 
Introduction to Quality Improvement Essentials
Introduction to Quality Improvement EssentialsIntroduction to Quality Improvement Essentials
Introduction to Quality Improvement Essentials
Excellence Foundation for South Sudan
 
Welcome to TechSoup New Member Orientation and Q&A (May 2024).pdf
Welcome to TechSoup   New Member Orientation and Q&A (May 2024).pdfWelcome to TechSoup   New Member Orientation and Q&A (May 2024).pdf
Welcome to TechSoup New Member Orientation and Q&A (May 2024).pdf
TechSoup
 
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
siemaillard
 

Recently uploaded (20)

CLASS 11 CBSE B.St Project AIDS TO TRADE - INSURANCE
CLASS 11 CBSE B.St Project AIDS TO TRADE - INSURANCECLASS 11 CBSE B.St Project AIDS TO TRADE - INSURANCE
CLASS 11 CBSE B.St Project AIDS TO TRADE - INSURANCE
 
TESDA TM1 REVIEWER FOR NATIONAL ASSESSMENT WRITTEN AND ORAL QUESTIONS WITH A...
TESDA TM1 REVIEWER  FOR NATIONAL ASSESSMENT WRITTEN AND ORAL QUESTIONS WITH A...TESDA TM1 REVIEWER  FOR NATIONAL ASSESSMENT WRITTEN AND ORAL QUESTIONS WITH A...
TESDA TM1 REVIEWER FOR NATIONAL ASSESSMENT WRITTEN AND ORAL QUESTIONS WITH A...
 
The Roman Empire A Historical Colossus.pdf
The Roman Empire A Historical Colossus.pdfThe Roman Empire A Historical Colossus.pdf
The Roman Empire A Historical Colossus.pdf
 
The Art Pastor's Guide to Sabbath | Steve Thomason
The Art Pastor's Guide to Sabbath | Steve ThomasonThe Art Pastor's Guide to Sabbath | Steve Thomason
The Art Pastor's Guide to Sabbath | Steve Thomason
 
Phrasal Verbs.XXXXXXXXXXXXXXXXXXXXXXXXXX
Phrasal Verbs.XXXXXXXXXXXXXXXXXXXXXXXXXXPhrasal Verbs.XXXXXXXXXXXXXXXXXXXXXXXXXX
Phrasal Verbs.XXXXXXXXXXXXXXXXXXXXXXXXXX
 
Instructions for Submissions thorugh G- Classroom.pptx
Instructions for Submissions thorugh G- Classroom.pptxInstructions for Submissions thorugh G- Classroom.pptx
Instructions for Submissions thorugh G- Classroom.pptx
 
The French Revolution Class 9 Study Material pdf free download
The French Revolution Class 9 Study Material pdf free downloadThe French Revolution Class 9 Study Material pdf free download
The French Revolution Class 9 Study Material pdf free download
 
Basic phrases for greeting and assisting costumers
Basic phrases for greeting and assisting costumersBasic phrases for greeting and assisting costumers
Basic phrases for greeting and assisting costumers
 
Fish and Chips - have they had their chips
Fish and Chips - have they had their chipsFish and Chips - have they had their chips
Fish and Chips - have they had their chips
 
Additional Benefits for Employee Website.pdf
Additional Benefits for Employee Website.pdfAdditional Benefits for Employee Website.pdf
Additional Benefits for Employee Website.pdf
 
Unit 2- Research Aptitude (UGC NET Paper I).pdf
Unit 2- Research Aptitude (UGC NET Paper I).pdfUnit 2- Research Aptitude (UGC NET Paper I).pdf
Unit 2- Research Aptitude (UGC NET Paper I).pdf
 
Operation Blue Star - Saka Neela Tara
Operation Blue Star   -  Saka Neela TaraOperation Blue Star   -  Saka Neela Tara
Operation Blue Star - Saka Neela Tara
 
Digital Tools and AI for Teaching Learning and Research
Digital Tools and AI for Teaching Learning and ResearchDigital Tools and AI for Teaching Learning and Research
Digital Tools and AI for Teaching Learning and Research
 
How to Create Map Views in the Odoo 17 ERP
How to Create Map Views in the Odoo 17 ERPHow to Create Map Views in the Odoo 17 ERP
How to Create Map Views in the Odoo 17 ERP
 
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
 
Thesis Statement for students diagnonsed withADHD.ppt
Thesis Statement for students diagnonsed withADHD.pptThesis Statement for students diagnonsed withADHD.ppt
Thesis Statement for students diagnonsed withADHD.ppt
 
special B.ed 2nd year old paper_20240531.pdf
special B.ed 2nd year old paper_20240531.pdfspecial B.ed 2nd year old paper_20240531.pdf
special B.ed 2nd year old paper_20240531.pdf
 
Introduction to Quality Improvement Essentials
Introduction to Quality Improvement EssentialsIntroduction to Quality Improvement Essentials
Introduction to Quality Improvement Essentials
 
Welcome to TechSoup New Member Orientation and Q&A (May 2024).pdf
Welcome to TechSoup   New Member Orientation and Q&A (May 2024).pdfWelcome to TechSoup   New Member Orientation and Q&A (May 2024).pdf
Welcome to TechSoup New Member Orientation and Q&A (May 2024).pdf
 
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
 

List and Dictionary in python

  • 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
  • 32. Sangita Panchal Dictionary in Python D1 = {'Ani': 12, 'John':32} D2 = {('Mia', 45, 32): [56, 23, 23, 66, 77]} D3 = {1:'Ginni', 2:'Anuj'} D4 = { 1: ('Mrinal', 65), 2: ('Sia', 89)} print(D1);print(D2) print(D3);print(D4) D5 = {[‘Ani’ , ’John’]: [12, 32 ]} print(D5) {'Ani': 12, 'John': 32} {('Mia', 45, 32): [56, 23, 23, 66, 77]} {1: 'Ginni', 2: 'Anuj'} {1: ('Mrinal', 65), 2: ('Sia', 89)} TypeError: unhashable type: 'list' 31
  • 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