Module 5 - Lists, Tuples, Sets and Dictionary - Python Programming
Module 5 - Lists, Tuples, Sets and Dictionary - Python Programming
9150132532
noornilo@gmail.com
Profameencse.weebly.com Noornilo Nafees 1
MODULE 5 – LISTS, TUPLES, SETS AND
DICTIONARY
At the end of this course students can able to
Understand the basic concepts of various
and Dictionaries.
Understand the relationship between List,
brackets.
The following syntax explains the creation of list.
Syntax:
Variable = [element-1, element-2, element-3 ……
element-n]
Noornilo Nafees 4
Example:
Marks = [10, 23, 41, 75]
Fruits = [“Apple”, “Orange”, “Mango”, “Banana”]
MyList = [ ]
Mylist1 = [“Welcome”, 3.14, 10, 20 ]
In the above example,
The list Marks has four integer elements
Second list Fruits has four string elements
Third MyList is an empty list.
Fourth Mylist1 contains multiple type elements.
Noornilo Nafees 5
Accessing List elements: Python assigns an automatic
index value for each element of a list begins with zero.
Index value can be used to access an element in a list.
Noornilo Nafees 6
To access an element from a list, write the name of the
list, followed by the index of the element enclosed
within square brackets.
Syntax:
List_Variable = [E1, E2, E3 …… En]
print (List_Variable[index of a element])
Example - Accessing single element:
Marks = [10, 23, 41, 75]
print (Marks[0])
10
Example - Accessing single element in reverse order):
Marks = [10, 23, 41, 75]
print (Marks[-1])
75
Noornilo Nafees 7
Example - Accessing all elements in the list using while
loop:
Loops are used to access all elements from a list.
The initial value of the loop must be zero.
Zero is the beginning index value of a list.
Marks = [10, 23, 41, 75]
i=0
while(i < 4):
◦ print (Marks[i])
◦ i=i+1
Output
10
23
41
75 Noornilo Nafees 8
In the above example, Marks list contains four integer
elements i.e., 10, 23, 41, 75.
Each element has an index value from 0.
The index value of the elements are 0, 1, 2, 3
respectively.
Here, the while loop is used to read all the elements.
The initial value of the loop is 0, and the test condition
is i < 4
As long as the test condition is true, the loop executes
Noornilo Nafees 9
During the first iteration, the value of i is zero, where
the condition is true.
Now, the statement print (Marks [i]) gets executed and
from 0 to 1.
Now, the flow of control shifts to the while statement
Noornilo Nafees 10
The following table shows that the execution of loop
and the value to be print.
Noornilo Nafees 11
Reverse Indexing: Python enables reverse or negative
indexing for the list elements.
The python sets -1 as the index value for the last element
in list and -2 for the preceding element and so on.
This is called as Reverse Indexing.
Marks = [10, 23, 41, 75]
i = -1
while(i >= -4):
◦ print (Marks[i])
◦ i = i + -1
Output
75
41
23
10
Noornilo Nafees 12
List Length:
The len( ) function in Python is used to find the length
Noornilo Nafees 13
Example: Program to display elements in a list using while
loop and len()
MySubject = [“Cloud Computing”, “Data Centre and
Virtualization”, “Computer Networks”, “Professional
Ethics”]
i=0
while (i < len(MySubject)):
◦ print (MySubject[i])
◦ i=i+1
Output
Cloud Computing
Data Centre and Virtualization
Computer Networks
Professional Ethics
Noornilo Nafees 14
Accessing elements using for loop: In Python, the for loop
is used to access all the elements in a list one by one.
Syntax:
for index_var in list:
◦ print (index_var)
Example:
Marks=[23, 45, 67, 78, 98]
for x in Marks:
◦ print( x )
Output
23
45
67
78
98
Noornilo Nafees 15
Changing list elements: In Python, the lists are
mutable, which means they can be changed.
A list element or range of elements can be changed or
altered by using simple assignment operator (=).
Syntax:
List_Variable [index of an element] = Value to be
changed
List_Variable [index from : index to] = Values to changed
Where, index from is the beginning index of the range;
index to is the upper limit of the range which is
excluded in the range.
For example, if you set the range [0:5] means, Python
takes only 0 to 4 as element index.
Thus, if you want to update the range of elements from
1 to 4, it should be specified as [1:5].
Noornilo Nafees 16
Example: Python program to update/change single value
MyList = [2, 4, 5, 8, 10]
print ("MyList elements before update... ")
Output:
for x in MyList: MyList elements before
print (x) update...
2
MyList[2] = 6
4
print ("MyList elements after updation... ") 5
for y in MyList: 8
10
print (y) MyList elements after
updation...
2
4
6
8
10
Noornilo Nafees 17
Python program to update/change range of values:
MyList = [1, 3, 5, 7, 9]
print ("List of Odd numbers... ")
Output:
for x in MyList:
List of Odd numbers...
print (x) 1
MyList[0:5] = 2,4,6,8,10 3
print ("List of Even numbers... ")
5
7
for y in MyList:
9
print (y) List of Even numbers...
2
4
6
8
10
Noornilo Nafees 18
Adding more elements in a list:
In Python, append() function is used to add a single
Noornilo Nafees 19
Example – append()
Mylist=[34, 45, 48]
Mylist.append(90)
print(Mylist)
Output:
[34, 45, 48, 90]
Example – extend()
Mylist.extend([71, 32, 29])
print(Mylist)
Output:
[34, 45, 48, 90, 71, 32, 29]
Noornilo Nafees 20
Inserting elements in a list:
If you want to include an element at your desired
Noornilo Nafees 21
Example: insert()
MyList=[34,98,47,'Kannan', 'Gowrisankar', 'Lenin',
'Sreenivasan' ]
print(MyList)
MyList.insert(3, 'Ramakrishnan')
print(MyList)
Output 1
[34, 98, 47, 'Kannan', 'Gowrisankar', 'Lenin', 'Sreenivasan']
Output 2
[34, 98, 47, 'Ramakrishnan', 'Kannan', 'Gowrisankar', 'Lenin',
'Sreenivasan']
In the above example, insert() function inserts a new element
‘Ramakrishnan’ at the index vaalue 3, ie. at the 4th position.
While inserting a new element in between the existing
elements, at a particular location, the existing elements shifts
one position to the right
Noornilo Nafees 22
Deleting elements from a list:
Syntax:
del List [index of an element]
# to delete a particular element
del List [index from : index to]
# to delete multiple elements
del List
# to delete entire list
Noornilo Nafees 23
Example: Deleting particular element in a list
MySubjects = ['Tamil', 'Hindi', 'Telugu', 'Maths']
print (MySubjects)
del MySubjects[1]
print (MySubjects)
Output 1
['Tamil', 'Hindi', 'Telugu', 'Maths']
Output 2
['Tamil', 'Telugu', 'Maths']
In the above example, the list MySubjects has been
created with four elements.
print statement shows all the elements of the list.
del MySubjects[1] statement, deletes an element whose
index value is 1 and the following print shows the
remaining elements of the list. Noornilo Nafees 24
Example: To delete multiple elements
MySubjects = ['Tamil', 'Hindi', 'Telugu', 'Maths']
del MySubjects[1:3]
print(MySubjects)
Output:
['Tamil‘,’Maths’]
In the above codes, del MySubjects[1:3] deletes the
Noornilo Nafees 25
Example: To delete entire list
del MySubjects
print(MySubjects)
Output:
Traceback (most recent call last):
File "<pyshell#9>", line 1, in <module>
print(MySubjects)
NameError: name 'MySubjects' is not defined
Here, del MySubjects, deletes the list MySubjects
entirely.
When you try to print the elements, Python shows an
deleted.
Noornilo Nafees 26
remove( )
The remove( ) function can also be used to delete one
element
MyList=[12,89,34,’Noor', ’Nilo', ’Nafees']
print(MyList)
Output 1
[12, 89, 34, ’Noor', ’Nilo', ’Nafees']
Output 2
MyList.remove(89)
print(MyList)
[12, 34, ’Noor', ’Nilo', ’Nafees']
Noornilo Nafees 27
pop( )
pop( ) function can be used to delete an element using
Noornilo Nafees 28
clear( )
The function clear( ) is used to delete all the elements
Noornilo Nafees 29
List and range ( ) function
The range( ) is a function used to generate a series of
values in Python.
Using range( ) function, you can create list with series
of values.
The range( ) function has three arguments.
Syntax: range (start value, end value, step value)
start value – beginning value of series. Zero is the
Noornilo Nafees 30
Example : Generating whole numbers up to 10
for x in range (1, 11):
◦ print(x)
Output
1
2
3
4
5
6
7
8
9
10
Noornilo Nafees 31
Example : Generating first 10 even numbers
for x in range (2, 11, 2):
◦ print(x)
Output
2
4
6
8
10
Noornilo Nafees 32
(i) Creating a list with series of values:
Using the range( ) function, you can create a list with
series of values.
To convert the result of range( ) function into list, we
Noornilo Nafees 33
Example:
Even_List = list(range(2,11,2))
print(Even_List)
Output:
[2, 4, 6, 8, 10]
Example : Generating squares of first 10 natural
numbers
squares = [ ]
for x in range(1,11):
◦ s = x ** 2
◦ squares.append(s)
print (squares)
Output:
[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
Noornilo Nafees 34
List comprehensions:
List comprehension is a simplest way of creating
Noornilo Nafees 35
Important list functions:
1. copy() - Returns a copy of the list
Syntax: List.copy()
MyList=[12, 12, 36]
x = MyList.copy()
print(x)
Output:
[12, 12, 36]
order.
Ascending is default.
sort() will affect the original list.
Noornilo Nafees 38
Example:
MyList=['Thilothamma', 'Tharani', 'Anitha', 'SaiSree',
'Lavanya']
MyList.sort( )
print(MyList)
MyList.sort(reverse=True)
print(MyList)
Output 1:
['Anitha', 'Lavanya', 'SaiSree', 'Tharani', 'Thilothamma']
Output 2:
['Thilothamma', 'Tharani', 'SaiSree', 'Lavanya', 'Anitha']
Noornilo Nafees 39
6. max() - Returns the maximum value in a list.
Syntax: max(list)
MyList=[21,76,98,23]
print(max(MyList))
Output:
98
Noornilo Nafees 41
Program 1: write a program that creates a list of
numbers from 1 to 20 that are divisible by 4
divBy4=[ ]
for i in range(21):
◦ if (i%4==0):
divBy4.append(i)
print(divBy4)
Output
[0, 4, 8, 12, 16, 20]
Noornilo Nafees 42
Program 2: Write a program to define a list of countries that
are a member of BRICS. Check whether a country is member
of BRICS or not?
country=["India", "Russia", "Srilanka", "China", "Brazil"]
member = input("Enter the name of the country: ")
if member in country:
◦ print(member, " is the member of BRICS")
else:
◦ print(member, " is not a member of BRICS")
Output 1
Enter the name of the country: India
India is the member of BRICS
Output 2
Enter the name of the country: Japan
Japan is not a member of BRICS
Noornilo Nafees 43
Python program to read marks of six subjects and to print the
marks scored in each subject and show the total marks
marks=[]
subjects=['Cloud Computing', 'Data Centre and Virtualization',
'Computer Networks', 'Professional Ethics', 'Operating
Systems', 'Python Programming']
for i in range(6):
◦ print("Enter marks of",subjects[i],":")
◦ m=int(input())
◦ marks.append(m)
for j in range(len(marks)):
◦ print(j+1,".",subjects[j],"Mark=",marks[j])
tot=sum(marks)
print("\nTotal Marks = ",tot)
avg=tot/6
print("Average marks = ",round(avg,2))
Noornilo Nafees 44
OUTPUT:
Enter marks of Cloud Computing :
89
Enter marks of Data Centre and Virtualization :
99
Enter marks of Computer Networks :
85
Enter marks of Professional Ethics :
87
Enter marks of Operating Systems :
97
Enter marks of Python Programming :
99
1 . Cloud Computing Mark = 89
2 . Data Centre and Virtualization Mark = 99
3 . Computer Networks Mark = 85
4 . Professional Ethics Mark = 87
5 . Operating Systems Mark = 97
6 . Python Programming Mark = 99
Total Marks = 556
Average marks = 92.67
Noornilo Nafees 45
Python program to read prices of 5 items in a list and
then display sum of all the prices, product of all the prices
and find the average
items=[]
prod=1
for i in range(5):
◦ print ("Enter price for item :”,(i+1))
◦ p=int(input())
◦ items.append(p)
for j in range(len(items)):
print("Price for item”,(j+1),” = Rs.”,items[j])
parenthesis.
Whether the elements defined within parenthesis or
Noornilo Nafees 54
(i) Creating tuples using tuple( ) function
The tuple( ) function is used to create Tuples from a list.
When you create a tuple, from a list, the elements should
be enclosed within square brackets.
Syntax:
Tuple_Name = tuple( [list elements] )
Example:
MyTup3 = tuple( [23, 45, 90] )
print(MyTup3)
Output: type ( ) function is used to know the data
(23, 45, 90) type of a python object.
type (MyTup3)
Output:
<class ‘tuple’>
Noornilo Nafees 55
(ii) Creating Single element tuple
While creating a tuple with a single element, add a comma at
the end of the element.
In the absence of a comma, Python will consider the element as
an ordinary data type; not a tuple.
Creating a Tuple with one element is called “Singleton” tuple.
Example:
MyTup4 = (10)
type(MyTup4)
Output:
<class 'int'>
Example:
MyTup5 = (10,)
type(MyTup5)
Output:
<class 'tuple'>
Noornilo Nafees 56
Accessing values in a Tuple: Each element of tuple has an index number
starting from zero.
The elements of a tuple can be easily accessed by using index number.
Example:
Tup1 = (12, 78, 91, “Tamil”, “Telugu”, 3.14, 69.48)
# to access all the elements of a tuple
print(Tup1)
(12, 78, 91, 'Tamil', 'Telugu', 3.14, 69.48)
#accessing selected elements using indices
print(Tup1[2:5])
(91, 'Tamil', 'Telugu')
#accessing from the first element up to the specified index value
print(Tup1[:5])
(12, 78, 91, 'Tamil', 'Telugu')
# accessing from the specified element up to the last element.
print(Tup1[4:])
('Telugu', 3.14, 69.48)
# accessing from the first element to the last element
print(Tup1[:])
(12, 78, 91, 'Tamil', 'Telugu', 3.14, 69.48)
Noornilo Nafees 57
Update Tuple:
As you know a tuple is immutable, the elements in a
Noornilo Nafees 58
Delete Tuple:
To delete an entire tuple, the del command can be used.
Syntax:
del tuple_name
Example:
Tup1 = (2,4,6,8,10)
print("The elements of Tup1 is ", Tup1)
del Tup1
print (Tup1)
Output:
The elements of Tup1 is (2, 4, 6, 8, 10)
Traceback (most recent call last):
File "D:/Python/Tuple Examp 1.py", line 4, in <module>
print (Tup1)
NameError: name 'Tup1' is not defined
Noornilo Nafees 59
Sorting a tuple: To sort a tuple in python use sorted() built in
function.
Pass the tuple as argument to sorted() function.
This function returns a list with the items of tuples sorted in
ascending order.
Then we should convert this list in to tuple using tuple()
function.
If reverse=true passed as second argument to sorted() function,
Example
it sorts the items in descending order.2:
Example 1: mytup1 = (23, 56, 2)
mytup1 = (23, 56, 2) result=sorted(mytup1,reverse=true)
result=sorted(mytup1) result=tuple(result)
print(result)
result=tuple(result)
Output:
print(result)
(56,23,2)
Output:
(2, 23, 56)
Noornilo Nafees 60
Tuple Assignment:
Tuple assignment is a powerful feature in Python.
It allows a tuple variable on the left of the assignment
Noornilo Nafees 61
Example 1:
(a, b, c) = (34, 90, 76)
print(a,b,c)
Output 1:
34 90 76
Example 2:
(x, y, z, p) = (2**2, 5/3+4, 15%2, 34>65)
print(x,y,z,p)
Output 2:
4 5.666666666666667 1 False
Note that, when you assign values to a tuple, ensure
◦ if i > 0:
Positive += (i, )
print("Positive Numbers: ", Positive)
Output:
Positive Numbers: (5, 6, 8, 3, 1)
Noornilo Nafees 67
SET:
In python, a set is another type of collection data type.
A Set is a mutable and an unordered collection of
Python.
Syntax:
Set_Variable = {E1, E2, E3 …….. En}
Noornilo Nafees 68
Example 1:
S1={1,2,3,'A',3.14} In the above examples, the set
print(S1) S1 is created with different types
Output 1:
of elements without duplicate
values.
{1, 2, 3, 3.14, 'A'}
Whereas in the set S2 is created
Example 2:
with duplicate values, but python
S2={1,2,2,'A',3.14}
accepts only one element among
print(S2) the duplications.
Output 2: Which means python removed
{1, 2, 'A', 3.14} the duplicate value, because a set
in python cannot have duplicate
elements.
Noornilo Nafees 69
Set Operations
Python supports the set operations such as Union,
sets
In python, the operator | is used to union of two sets.
The function union( ) is also used to join two sets in
python.
Noornilo Nafees 70
Program to Join (Union) two sets using union
operator
set_A={2,4,6,8}
set_B={'A', 'B', 'C', 'D'}
U_set=set_A|set_B
print(U_set)
Output:
{2, 4, 6, 8, 'A', 'D', 'C', 'B'}
Noornilo Nafees 71
Program to Join (Union) two sets using union function
set_A={2,4,6,8}
set_B={'A', 'B', 'C', 'D'}
set_U=set_A.union(set_B)
print(set_U)
Output:
{'D', 2, 4, 6, 8, 'B', 'C', 'A'}
Noornilo Nafees 72
(ii) Intersection: It includes the common elements in
two sets
The operator & is used to intersect two sets in python.
The function intersection( ) is also used to intersect
Noornilo Nafees 73
Program to insect two sets using intersection
operator
set_A={'A', 2, 4, 'D'}
set_B={'A', 'B', 'C', 'D'}
print(set_A & set_B)
Output:
{'A', 'D'}
Program to insect two sets using intersection function
set_A={'A', 2, 4, 'D'}
set_B={'A', 'B', 'C', 'D'}
print(set_A.intersection(set_B))
Output:
{'A', 'D'}
Noornilo Nafees 74
(iii) Difference
It includes all elements that are in first set (say set A)
operation in python.
The function difference( ) is also used to difference
operation.
Noornilo Nafees 75
Program to difference of two sets using minus
operator
set_A={'A', 2, 4, 'D'}
set_B={'A', 'B', 'C', 'D'}
print(set_A - set_B)
Output:
{2, 4}
Program to difference of two sets using difference
function
set_A={'A', 2, 4, 'D'}
set_B={'A', 'B', 'C', 'D'}
print(set_A.diff erence(set_B))
Output:
{2, 4}
Noornilo Nafees 76
(iv) Symmetric difference:
It includes all the elements that are in two sets (say sets
A and B) but not the one that are common to two sets.
The caret (^) operator is used to perform symmetric
difference set operation in python.
The function symmetric_difference( ) is also used to do
the same operation.
Program to perform symmetric difference of two sets
using caret operator
set_A={'A', 2, 4, 'D'}
set_B={'A', 'B', 'C', 'D'}
print(set_A ^ set_B)
Output:
{2, 4, 'B', 'C'}
Noornilo Nafees 77
Program to difference of two sets using symmetric
difference function
set_A={'A', 2, 4, 'D'}
set_B={'A', 'B', 'C', 'D'}
print(set_A.symmetric_difference(set_B))
Output:
{2, 4, 'B', 'C'}
Noornilo Nafees 78
Dictionaries:
In python, a dictionary is a mixed collection of
elements.
Unlike other collection data types such as a list or
'Class':'XII', 'Marks':'451'}
Noornilo Nafees 80
Dictionary Comprehensions
In Python, comprehension is another way of creating
dictionary.
The following is the syntax of creating such dictionary.
Syntax
Dict = { expression for variable in sequence [if
condition] }
The if condition is optional and if specified, only those
Noornilo Nafees 81
Example:
Dict = { x : 2 * x for x in range(1,10)}
Output:
{1: 2, 2: 4, 3: 6, 4: 8, 5: 10, 6: 12, 7: 14, 8: 16, 9: 18}
Accessing, Adding, Modifying and Deleting elements
from a Dictionary
Accessing all elements from a dictionary is very similar
elements.
If you want to access a particular element, square
Noornilo Nafees 82
Program to access all the values stored in a dictionary
MyDict = { 'Reg_No': '1221',
'Name' : ‘Nafees',
'School' : 'CGHSS',
'Address' : 'Rotler St., Chennai 112' }
print(MyDict)
print("Register Number: ", MyDict['Reg_No'])
print("Name of the Student: ", MyDict['Name'])
print("School: ", MyDict['School'])
print("Address: ", MyDict['Address'])
Output:
{'Reg_No': '1221', 'Name': ‘Nafees', 'School': 'CGHSS', 'Address':
'Rotler St., Chennai 112'}
Register Number: 1221
Name of the Student: Nafees
School: CGHSS
Address: Rotler St., Chennai 112 Noornilo Nafees 83
Adding elements in dictionary:
In an existing dictionary, you can add more values by
Noornilo Nafees 84
Program to add a new value in the dictionary
MyDict = { 'Reg_No': '1221',
'Name' : ‘Nafees',
'School' : 'CGHSS', 'Address' : '
Rotler St., Chennai 112'}
print(MyDict)
print("Register Number: ", MyDict['Reg_No'])
print("Name of the Student: ", MyDict['Name'])
MyDict['Class'] = 'XII - A' # Adding new value
print("Class: ", MyDict['Class']) # Printing newly
added value
print("School: ", MyDict['School'])
print("Address: ", MyDict['Address'])
Noornilo Nafees 85
Modification of value in python dictionary:
Modification of a value in dictionary is very similar as
adding elements.
When you assign a value to a key, it will simply
particular element.
The clear( ) function is used to delete all the elements
in a dictionary.
To remove the dictionary, you can use del keyword
Noornilo Nafees 86
Deletion of elements in dictionary:
Syntax:
# To delete a particular element.
del dictionary_name[key]
# To delete all the elements
dictionary_name.clear( )
# To delete an entire dictionary
del dictionary_name
Noornilo Nafees 87
Program to delete elements from a dictionary and finally deletes the
dictionary.
Dict = {'Roll No' : 12001, 'SName' : 'Meena', 'Mark1' : 98, 'Marl2' : 86}
print("Dictionary elements before deletion: \n", Dict)
del Dict['Mark1'] # Deleting a particular element
print("Dictionary elements after deletion of a element: \n", Dict)
Dict.clear() # Deleting all elements
print("Dictionary after deletion of all elements: \n", Dict)
del Dict # Deleting entire dictionary
print(Dict)
Output:
Dictionary elements before deletion:
{'Roll No': 12001, 'SName': 'Meena', 'Mark1': 98, 'Marl2': 86}
Dictionary elements after deletion of a element:
{'Roll No': 12001, 'SName': 'Meena', 'Marl2': 86}
Dictionary after deletion of all elements:
{}
Traceback (most recent call last):
File "E:/Python/Dict_Test_02.py", line 8, in <module>
print(Dict)
NameError: name 'Dict' is not defined Noornilo Nafees 88
Write a program that prints the maximum and
minimum value in a dictionary.
mydict = {"Ameen": 18, "Nilo": 10, "Nafees": 13}
print("Data in Dictionary:\n",mydict)
dmax = max(mydict, key=mydict.get)
dmin = min(mydict, key=mydict.get)
print("Maximum value:",dmax,":",mydict.get(dmax))
print("Minimum value:",dmin,":",mydict.get(dmin))
Output:
Data in Dictionary:
{'Ameen': 18, 'Nilo': 10, 'Nafees': 13}
Maximum value: Ameen : 18
Minimum value: Nilo : 10
Noornilo Nafees 89
Difference between List and Dictionary:
List is an ordered set of elements. But, a dictionary is a
Noornilo Nafees 90
Points to remember:
Python programming language has four collections of
brackets.
Each element has a unique value called index number
Noornilo Nafees 91
The append ( ), extend ( ) and insert ( ) functions are used to
include more elements in a List.
The del, remove ( ) and pop ( ) are used to delete elements
from a list.
The range ( ) function is used to generate a series of values.
Tuples consists of a number of values separated by comma
and enclosed within parentheses.
Iterating tuples is faster than list.
The tuple ( ) function is also used to create Tuples from a list.
Creating a Tuple with one element is called “Singleton”
tuple.
A Set is a mutable and an unordered collection of elements
without duplicates.
A set is created by placing all the elements separated by
comma within a pair of curly brackets.
A dictionary is a mixed collection of elements.
Noornilo Nafees 92
Module 5 – Quiz
1. Pick odd one in connection with collection data type
(a) List (b) Tuple (c) Dictionary (d) Loop
2. Let list1=[2,4,6,8,10], then print(list1[-2]) will result
code?
S=[x**2 for x in range(5)]
print(S)
(a) [0,1,2,4,5] (b) [0,1,4,9,16] (c) [0,1,4,9,16,25] (d)
[1,4,9,16,25]
8. What is the use of type() function in python?
(a) To create a Tuple
(b) To know the type of an element in tuple.
(c) To know the data type of python object.
(d) To create a list.
Noornilo Nafees 94
9. Which of the following statement is not correct?
(a) A list is mutable
(b) A tuple is immutable.
(c) The append() function is used to add an element.
(d) The extend() function is used in tuple to add elements in a
list.
10. Let setA={3,6,9}, setB={1,3,9}. What will be the result of the
following snippet?
print(setA|setB)
(a) {3,6,9,1,3,9} (b) {3,9} (c) {1} (d) {1,3,6,9}
11. Which of the following set operation includes all the
elements that are in two sets but not the one that are common
to two sets?
(a) Symmetric difference (b) Difference
(c) Intersection (d) Union
12. The keys in Python, dictionary is specified by
(a) = (b) ; (c)+ (d) : Noornilo Nafees 95
Module 5 : Hands on
1. Write a program to remove duplicates from a list.
Way1: Using temporary list
my_list = [1, 2, 3, 1, 2, 4, 5, 4 ,6, 2]
print("List Before removing duplicates ", my_list)
temp_list = []
for i in my_list:
◦ if i not in temp_list:
temp_list.append(i)
my_list = temp_list
print("List After removing duplicates ", my_list)
Output:
List Before removing [1, 2, 3, 1, 2, 4, 5, 4, 6, 2]
List After removing duplicates [1, 2, 3, 4, 5, 6]
Noornilo Nafees 96
Way2: Using set() function
my_list = [1, 2, 3, 1, 2, 4, 5, 4 ,6, 2]
print("List Before removing duplicates ", my_list)
my_final_list = set(my_list)
print("List After removing duplicates ", list(my_final_list))
Output:
List Before removing duplicates [1, 2, 3, 1, 2, 4, 5, 4, 6, 2]
List After removing duplicates [1, 2, 3, 4, 5, 6]
Noornilo Nafees 97
2. Write a program that prints the maximum value in
a Tuple.
mytup1 = (23, 56, 2)
print(“Maximum value of tuple is :”,max(mytup1))
Output:
Maximum value of tuple is :56
Noornilo Nafees 98
3. Write a program that finds the sum of all the
numbers in a Tuples using while loop.
sum=0
mytup1 = (10,20,30,40,50)
print(“Numbers in the tuple are:",mytup1)
i=0
while(i<len(mytup1)):
◦ sum=sum+mytup1[i]
◦ i=i+1
print("Sum of all the numbers in the tuple is:",sum)
Output:
Numbers in the tuple are: (10, 20, 30, 40, 50)
Sum of all the numbers in the tuple is: 150
Noornilo Nafees 99
4. Write a program that finds sum of all even numbers in a list.
Way 1:
mylist=[]
evenlist=[]
n=int(input("Enter total count of numbers to be added in the
list:"))
print("Enter the numbers one by one:")
for i in range(1,n+1):
◦ i=int(input())
◦ mylist.append(i)
print("Numbers in the list:",mylist)
◦ for i in range(0,len(mylist)):
◦ if(mylist[i]%2==0):
◦ evenlist.append(mylist[i])
print("Even number in the list :",evenlist)
print("Sum of even number in the list is:",sum(evenlist))
Noornilo Nafees 10
0
Output:
Enter total count of numbers to be added in the list:6
Enter the numbers one by one:
10
20
30
40
50
60
Numbers in the list: [10, 20, 30, 40, 50, 60]
Even number in the list : [10, 20, 30, 40, 50, 60]
Sum of even number in the list is: 210
Noornilo Nafees 10
1
Way 1:
evenlist = list(range(2,11,2))
print("List of even numbers in the list:",evenlist)
print("Sum of even numbers in the list:",sum(evenlist))
Output:
List of even numbers in the list: [2, 4, 6, 8, 10]
Sum of even numbers in the list: 30
Noornilo Nafees 10
2
5. Write a program that reverse a list using a loop.
mylist=[10,20,30,40,50,"Ameen"]
revlist=[]
print("List of elements in the list :",mylist)
for i in range(-1,-(len(mylist)+1),-1):
◦ revlist.append(mylist[i])
print("List of elements in the list after
reversing:",revlist)
Output:
List of elements in the list : [10, 20, 30, 40, 50,
'Ameen']
List of elements in the list after reversing: ['Ameen', 50,
Noornilo Nafees 10
3
6. Write a program to insert a value in a list at the specified
location.
mylist=[10,20,30,40,50,"Ameen"]
print("Elements in the list",mylist)
print("Enter the index and value to be inserted one by one:")
index=int(input())
value=input()
mylist.insert(index,value)
print("Elements in the list after adding new element at specified
location :",mylist)
Output:
Elements in the list [10, 20, 30, 40, 50, 'Ameen']
Enter the index and value to be inserted one by one:
5
Nafees
Elements in the list after adding new element at specified location :
[10, 20, 30, 40, 50, 'Nafees', 'Ameen']
Noornilo Nafees 10
4
7. Write a program that creates a list of numbers from
1 to 50 that are either divisible by 3 or divisible by 6.
mylist=[]
for i in range(1,51):
◦ if((i%3==0)or(i%6==0)):
mylist.append(i)
print("list of numbers from 1 to 50 that are either
3 or divisible by 6 are:
[3, 6, 9, 12, 15, 18, 21, 24, 27, 30, 33, 36, 39, 42, 45,
48]
Noornilo Nafees 10
5
8. Write a program to create a list of numbers in the range 1 to 20.
Then delete all the numbers from the list that are divisible by 3.
mylist=[]
for i in range(1,21):
◦ mylist.append(i)
print("list of numbers from 1 to 20:\n",mylist)
for i in mylist:
◦ if(i%3==0):
mylist.remove(i)
print("list of numbers from 1 to 20 after\ndeleting all the numbers
from the list that are divisible by 3:\n",mylist)
Output:
list of numbers from 1 to 20:
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20]
list of numbers from 1 to 20 after
deleting all the numbers from the list that are divisible by 3:
[1, 2, 4, 5, 7, 8, 10, 11, 13, 14, 16, 17, 19, 20]
Noornilo Nafees 10
6
9. Write a program that counts the number of times a
value appears in the list. Use a loop to do the same.
mylist=[10,40,20,50,30,60,10,40,20,50,60,10]
count=0print("List:",mylist)
f=int(input("Enter a value to find no of times it appeared
in this list:"))
for i in mylist:
◦ if(f==i):
count+=1
print(f,"appeared",count,"times")
Output:
List: [10, 40, 20, 50, 30, 60, 10, 40, 20, 50, 60, 10]
Enter a value to find no of times it appeared in this list:10
10 appeared 3 times
Noornilo Nafees 10
7
10. Write a program that prints the maximum and
minimum value in a dictionary.
mydict = {"Ameen": 18, "Nilo": 10, "Nafees": 13}
print("Data in Dictionary:\n",mydict)
dmax = max(mydict, key=mydict.get)
dmin = min(mydict, key=mydict.get)
print("Maximum value:",dmax,":",mydict.get(dmax))
print("Minimum value:",dmin,":",mydict.get(dmin))
Output:
Data in Dictionary:
{'Ameen': 18, 'Nilo': 10, 'Nafees': 13}
Maximum value: Ameen : 18
Minimum value: Nilo : 10
Noornilo Nafees 10
8