0% found this document useful (0 votes)
4 views

Module 5 - Lists, Tuples, Sets and Dictionary - Python Programming

unit 5
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views

Module 5 - Lists, Tuples, Sets and Dictionary - Python Programming

unit 5
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 108

PYTHON PROGRAMMING:

MODULE 5 – LISTS, TUPLES, SETS AND


DICTIONARY
Prof J. Noorul Ameen M.E,(Ph.D), EMCAA, MISTE, D.Acu.,
Assistant Professor/CSE
Member – Centre for Technology & Capability Development
E.G.S Pillay Engineering College, Nagapattinam

9150132532
[email protected]
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

collection data types in python such as List,


Tuples, sets and Dictionary.
 Work with List, Tuples, sets and Dictionaries

using variety of functions.


 Write Python programs using List, Tuples, sets

and Dictionaries.
 Understand the relationship between List,

Tuples and Dictionaries.


Noornilo Nafees 2
Introduction to List
 Python programming language has four collections of
data types such as List, Tuples, Set and Dictionary.
 It is an ordered collection of values enclosed within
square brackets [ ].
 Each value of a list is called as element.
 It can be of any type such as numbers, characters,
strings and even the nested lists as well.
 The elements can be modified or mutable which means
the elements can be replaced, added or removed.
 Every element rests at some position in the list.
 The position of an element is indexed with numbers
beginning with zero which is used to locate and access
a particular element.
Noornilo Nafees 3
 Creating a List in Python:
 In python, a list is created by using square bracket.
 The elements of list should be specified within square

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.

In python, index value is an integer number which can


be positive or negative.
 Example: Marks = [10, 23, 41, 75]

 Positive value of index counts from the beginning of


the list and negative value means counting backward
from end of the list (i.e. in reverse order).

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

and prints the corresponding output.

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

prints the value of Marks [0] element 10.


 The next statement i = i + 1 increments the value of i

from 0 to 1.
 Now, the flow of control shifts to the while statement

for checking the test condition.


 The process repeats to print the remaining elements of

Marks list until the test condition of while loop


becomes false.

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

of a list. (i.e., the number of elements in a list).


 If a list contains another list as an element, len( )

returns that inner list as a single element.


 Example:
 MySubject = [“Cloud Computing”, “Data Centre and

Virtualization”, “Computer Networks”, “Professional


Ethics”]
 len(MySubject)
 Output
 4

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

element and extend() function is used to add more


than one element to an existing list.
 Syntax:
 List.append (element to be added)
 List.extend ([elements to be added])
 In extend() function, multiple elements should be

specified within square bracket as arguments of the


function.

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

position, you can use insert () function.


 The insert() function is used to insert an element at

any position of a list.


 Syntax:
 List.insert (position index, element)

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

second and third elements from the list. The upper


limit of index is specified within square brackets, will
be taken as -1 by the python.

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

error as the list is not defined.


 Which means, the list MySubjects has been completely

deleted.
Noornilo Nafees 26
 remove( )
 The remove( ) function can also be used to delete one

or more elements if the index value is not known.


 Syntax: List.remove(element) # to delete a particular

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

the given index value.


 pop( ) function deletes and returns the last element of

a list if the index is not given.


 Syntax: List.pop(index of an element)
 MyList=[12,34,’Noor', ’Nilo', ’Nafees']
 MyList.pop(1)
 Output 1
 34
 print(MyList)
 Output 1
 [12,’Noor', ’Nilo', ’Nafees']

Noornilo Nafees 28
 clear( )
 The function clear( ) is used to delete all the elements

in list, it deletes only the elements and retains the list.


 Remember that, the del statement deletes entire list.
 Syntax: List.clear()
 MyList=[12,34,’Noor', ’Nilo', ’Nafees']
 MyList.clear( )
 print(MyList)
 Output:
 []

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

default beginning value.


 end value – upper limit of series. Python takes the

ending value as upper limit – 1.


 step value – It is an optional argument, which is used

to generate different interval of values.

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

need one more function called list( ).


 The list( ) function makes the result of range( ) as a list.
 Syntax:
 List_Varibale = list ( range ( ) )

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

sequence of elements that satisfy a certain condition.


 Syntax:
 List = [ expression for variable in range ]
 Example : Generating squares of first 10 natural

numbers using the concept of List comprehension


 squares = [ x ** 2 for x in range(1,11) ]
 print (squares)
 Output:
 [1, 4, 9, 16, 25, 36, 49, 64, 81, 100]

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]

 2. count() - Returns the number of similar elements present in the


last.
 Syntax: List.count(value)
 MyList=[36 ,12 ,12]
 x = MyList.count(12)
 print(x)
 Output:
 2 Noornilo Nafees 36
 3. index () Returns the index value of the first recurring
element
 Syntax: List.index(element)
 MyList=[36 ,12 ,12]
 x = MyList.index(12)
 print(x)
 Output:
 1
 4. reverse () - Reverses the order of the element in the list.
 Syntax: List.reverse( )
 MyList=[36 ,23 ,12]
 MyList.reverse()
 print(MyList)
 Output:
 [12 ,23 ,36] Noornilo Nafees 37
 5. sort() - Sorts the element in list
 Syntax: List.sort(reverse=True|False)
 Both arguments are optional
 If reverse is set as True, list sorting is in descending

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

 7. min() - Returns the minimum value in a list.


 Syntax: min(list)
 MyList=[21,76,98,23]
 print(min(MyList))
 Output:
 21
Noornilo Nafees 40
 8. sum() - Returns the sum of values in a list.
 Syntax: sum(list)
 MyList=[21,76,98,23]
 print(sum(MyList))
 Output:
 218

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])

 prod = prod * items[j]

 print("Sum of all prices = Rs.", sum(items))


 print("Product of all prices = Rs.", prod)
 print("Average of all prices = Rs.",sum(items)/len(items))
Noornilo Nafees 46
 Output:
 Enter price for item 1 :
 5
 Enter price for item 2 :
 10
 Enter price for item 3 :
 15
 Enter price for item 4 :
 20
 Enter price for item 5 :
 25
 Price for item 1 = Rs. 5
 Price for item 2 = Rs. 10
 Price for item 3 = Rs. 15
 Price for item 4 = Rs. 20
 Price for item 5 = Rs. 25
 Sum of all prices = Rs. 75
 Product of all prices = Rs. 375000
 Average of all prices = Rs. 15.0
Noornilo Nafees 47
 Python program to count the number of employees earning more
than 1 lakh per annum. The monthly salaries of n number of
employees are given
 count=0
 n=int(input("Enter no. of employees: "))
 print("No. of Employees",n)
 salary=[]
 for i in range(n):
◦ print("Enter Monthly Salary of Employee”,(i+1),”Rs: ")
◦ s=int(input())
◦ salary.append(s)
 for j in range(len(salary)):
◦ annual_salary = salary[j] * 12
◦ print ("Annual Salary of Employee”,(j+1),” is:Rs:”,annual_salary))
◦ if (annual_salary >= 100000):
◦ count = count + 1
 print(count,“ Employees out of”,n,” employees are earning more than
Rs. 1 Lakh per annum") Noornilo Nafees 48
 Output:
 Enter no. of employees: 5
 No. of Employees 5
 Enter Monthly Salary of Employee 1 Rs.:
 3000
 Enter Monthly Salary of Employee 2 Rs.:
 9500
 Enter Monthly Salary of Employee 3 Rs.:
 12500
 Enter Monthly Salary of Employee 4 Rs.:
 5750
 Enter Monthly Salary of Employee 5 Rs.:
 8000
 Annual Salary of Employee 1 is:Rs. 36000
 Annual Salary of Employee 2 is:Rs. 114000
 Annual Salary of Employee 3 is:Rs. 150000
 Annual Salary of Employee 4 is:Rs. 69000
 Annual Salary of Employee 5 is:Rs. 96000
 2 Employees out of 5 employees are earning more than Rs. 1 Lakh per
annum
Noornilo Nafees 49
 Write a program to create a list of numbers in the range 1
to 10. Then delete all the even numbers from the list and
print the final list.
 Num = []
 for x in range(1,11):
◦ Num.append(x)
◦ print("The list of numbers from 1 to 10 = ", Num)
 for i in Num:
◦ if(i%2==0):
 Num.remove(i)
 print("The list after deleting even numbers = ", Num)
 Output:
The list of numbers from 1 to 10 = [1, 2, 3, 4, 5, 6, 7, 8, 9,
10]
 The list after deleting even numbers = [1, 3, 5, 7, 9]
Noornilo Nafees 50
 Write a program to generate Fibonacci series and store it in a list. Then find
the sum of all values.
 fib=[]
 Number = int(input("Please Enter the Range Number: "))
 i=0 Output:
 First_Value = 0 Please Enter the Range Number: 5
 Second_Value = 1 Fibonacci series up to 5 is [0, 1, 1, 2, 3]
 while(i < Number):
Sum of all values in the Fibonacci series is: 7
◦ if(i <= 1):
 Next = i
 fib.append(Next)
◦ else:
 Next = First_Value + Second_Value
 fib.append(Next)
 First_Value = Second_Value
 Second_Value = Next
◦ i=i+1
 print("Fibonacci series up to",Number,"is",fib)
 print("Sum of all values in the Fibonacci series is:",sum(fib))
Noornilo Nafees 51
 Tuples
 Tuples consists of a number of values separated by
comma and enclosed within parentheses.
 Tuple is similar to list, values in a list can be changed but
not in a tuple.
 Comparison of Tuples with List :
 The elements of a list are changeable (mutable) whereas
the elements of a tuple are unchangeable (immutable),
this is the key difference between tuples and list.
 The elements of a list are enclosed within square
brackets. But, the elements of a tuple are enclosed by
parenthesis.
 Iterating tuples is faster than list.
 Most of the functions used in List can be applicable for
tuples.
Noornilo Nafees 52
 Creating Tuples
 In tuples, elements may be enclosed by parenthesis.
 The elements of a tuple can be even defined without

parenthesis.
 Whether the elements defined within parenthesis or

without parenthesis, there is no difference in it's


function.
 Syntax:
 # Empty tuple
 Tuple_Name = ( )
 # Tuple with n number elements
 Tuple_Name = (E1, E2, E2 ……. En)
 # Elements of a tuple without parenthesis
 Tuple_Name = E1, E2, E3 ….. En
Noornilo Nafees 53
 Example 1:
 MyTup1 = (23, 56, 89, 'A', 'E', 'I', “Networks")
 print(MyTup1)
 Output:
 (23, 56, 89, 'A', 'E', 'I', ‘Networks')
 Example 1:
 MyTup2 = 23, 56, 89, 'A', 'E', 'I', “Networks"
 print (MyTup2)
 Output:
 (23, 56, 89, 'A', 'E', 'I', ‘Networks')

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

tuple cannot be changed.


 Instead of altering values in a tuple, joining two tuples

or deleting the entire tuple is possible.


 Example:
 Program to join two tuples
 Tup1 = (2,4,6,8,10)
 Tup2 = (1,3,5,7,9)
 Tup3 = Tup1 + Tup2
 print(Tup3)
 Output
 (2, 4, 6, 8, 10, 1, 3, 5, 7, 9)

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

operator to be assigned to the values on the right side


of the assignment operator.
 Each value is assigned to its respective variable.

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

that the number of values on both sides of the


assignment operator are same; otherwise, an error will
be generated by Python.
Noornilo Nafees 62
 Returning multiple values in Tuples: A function can return only
one value at a time, but Python returns more than one value
from a function.
 Python groups multiple values and returns them together.
 Program to return the maximum as well as minimum values in
a list
 def Min_Max(n):
◦ a = max(n)
◦ b = min(n)
◦ return(a, b)
 Num = (12, 65, 84, 1, 18, 85, 99)
 (Max_Num, Min_Num) = Min_Max(Num)
 print("Maximum value = ", Max_Num)
 print("Minimum value = ", Min_Num)
 Output:
 Maximum value = 99
 Minimum value = 1 Noornilo Nafees 63
 Nested Tuples:
 In Python, a tuple can be defined inside another tuple; called
Nested tuple.
 In a nested tuple, each tuple is considered as an element.
 The for loop will be useful to access all the elements in a nested
tuple.
 Example:
 Toppers = (("Vinodini", "XII-F", 98.7), ("Soundarya", "XII-H",
97.5),
 ("Tharani", "XII-F", 95.3), ("Saisri", "XII-G", 93.8))
 for i in Toppers:
◦ print(i)
 Output:
 ('Vinodini', 'XII-F', 98.7)
 ('Soundarya', 'XII-H', 97.5)
 ('Tharani', 'XII-F', 95.3)
 ('Saisri', 'XII-G', 93.8) Noornilo Nafees 64
 Write a program to swap two values using tuple
assignment
 a = int(input("Enter value of A: "))
 b = int(input("Enter value of B: "))
 print("Value of A = ", a, "\n Value of B = ", b)
 (a, b) = (b, a)
 print("Value of A = ", a, "\n Value of B = ", b)
 Output:
 Enter value of A: 54
 Enter value of B: 38
 Value of A = 54
 Value of B = 38
 Value of A = 38
 Value of B = 54
Noornilo Nafees 65
 Write a program using a function that returns the area
and circumference of a circle whose radius is passed as
an argument using tuple assignment.
 pi = 3.14
 def Circle(r):
◦ return (pi*r*r, 2*pi*r)
 radius = float(input("Enter the Radius: "))
 (area, circum) = Circle(radius)
 print ("Area of the circle = ", area)
 print ("Circumference of the circle = ", circum)
 Output:
 Enter the Radius: 5
 Area of the circle = 78.5
 Circumference of the circle = 31.400000000000002
Noornilo Nafees 66
 Write a program that has a tuple of positive and
negative numbers. Create a new tuple that has only
positive numbers from the existing tuple.
 Numbers = (5, -8, 6, 8, -4, 3, 1)
 Positive = ( )
 for i in Numbers:

◦ 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

elements without duplicates.


 Creating a Set:
 A set is created by placing all the elements separated

by comma within a pair of curly brackets.


 The set( ) function can also used to create sets in

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,

Intersection, difference and Symmetric difference.


 (i) Union: It includes all elements from two or more

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

two sets in python.

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)

but not in the second set (say set B)


 The minus (-) operator is used to difference set

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

tuple, the dictionary type stores a key along with its


element.
 The keys in a Python dictionary is separated by a colon

( : ) while the commas work as a separator for the


elements.
 The key value pairs are enclosed with curly braces { }.
 Key in the dictionary must be unique case sensitive
 Syntax of defining a dictionary:
 Dictionary_Name = { Key_1: Value_1,Key_2:Value_2,
 ……..Key_n:Value_n}
Noornilo Nafees 79
 Creating a Dictionary
 # Empty dictionary
 Dict1 = { }
 # Dictionary with Key
 Dict_Stud = { 'RollNo': '1234', 'Name':'Murali',

'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

values in the sequence are evaluated using the


expression which satisfy the condition.

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

as Lists and Tuples.


 Simple print function is used to access all the

elements.
 If you want to access a particular element, square

brackets can be used along with key.

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

simply assigning the value along with key.


 Syntax: dictionary_name [key] = value/element

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

overwrite the old value.


 Deletion of elements in dictionary:
 In Python dictionary, del keyword is used to delete a

particular element.
 The clear( ) function is used to delete all the elements

in a dictionary.
 To remove the dictionary, you can use del keyword

with dictionary name.

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

data structure that is used for matching one element


(Key) with another (Value).
 The index values can be used to access a particular

element. But, in dictionary key represents index.


Remember that, key may be a number of a string.

Noornilo Nafees 90
 Points to remember:
 Python programming language has four collections of

data types such as List, Tuple, Set and Dictionary.


 A list is known as a “sequence data type”.
 Each value of a list is called as element.
 The elements of list should be specified within square

brackets.
 Each element has a unique value called index number

begins with zero.


 Python allows positive and negative values as index.
 Loops are used access all elements from a list.
 The “for” loop is a suitable loop to access all the

elements one by one.

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

in (a) 10 (b) 8 (c) 4 (d) 6


 3. Which of the following function is used to count the

number of elements in a list?


 (a) count() (b) find() (c)len() (d) index()
 4. If List=[10,20,30,40,50] then List[2]=35 will result
 (a) [35,10,20,30,40,50] (b) [10,20,30,40,50,35]
 (c) [10,20,35,40,50] (d) [10,35,30,40,50]
 5. If List=[17,23,41,10] then List.append(32) will result
 (a) [32,17,23,41,10] (b) [17,23,41,10,32]
 (c) [10,17,23,32,41] (d) [41,32,23,17,10]
Noornilo Nafees 93
 6. Which of the following Python function can be used
to add more than one element within an existing list?
 (a) append() (b) append_more() (c)extend() (d) more()
 7. What will be the result of the following Python

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,

40, 30, 20, 10]

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

divisible by 3 or divisible by 6 are:\n",mylist)


 Output:
 list of numbers from 1 to 50 that are either divisible by

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

You might also like