Aswini D
Assistant Professor
Tuples
Aswini D
Assistant Professor
Tuples are sequences, just like lists.
A tuple contains a sequence of items of any data type
The difference between the tuple and list is that we
cannot change the elements of a tuple once it is assigned
whereas in a list, elements can be changed.
Elements in the tuples are fixed
Once it is created, we cannot add or remove elements
Hence tuples are immutable
Since, tuples are quite similar to lists, both of them are used
in similar situations as well.
However, there are certain advantages of implementing a
tuple over a list.
Tuples that contain immutable elements can be used as
key for a dictionary.With list, this is not possible.
If you have data that doesn't change, implementing it as
tuple will guarantee that it remains write-protected.
 A tuple is created by placing all the items (elements) inside a parentheses (),
separated by comma.
 The parentheses are optional but is a good practice to write it.
 A tuple can have any number of items and they may be of different types (integer,
float, list, string etc.).
# empty tule
T1=()
# tuples having of integers
T2 = (1, 2, 3)
# tuple with mixed datatypes
T3 = (1, "Hello", 3.4)
# nested tuple
T4 = (“welcome", (8, 4, 6))
Method -1
Method-2
# empty tuple
T1= tuple()
# tuple function with string as
arguments
my_list = tuple(“welcome”)
• Creating a tuple with one
element is a bit tricky.
• Single element should be
followed by comma
>>> T1=(4)
>>> type(T1)
<class 'int'>
>>> T1=(4,)
>>> type(T1)
<class 'tuple'>
we can access the elements of a tuple using
index & slice operator
Indexing
 We can use the index operator [] to access an item in a tuple
where the index starts from 0.
>>> t1=(10,20,30)
>>> print(t1[2])
30
>>> print(t1[-3])
10
Slicing
 We can access a range of items in a tuple by using the slicing
operator - colon ":“
>>>print(t1[0:2:1])
(10, 20)
#nested tuple
>>> t1=(10,20,(15,25))
>>> print(t1[2][0])
15
 Unlike lists, tuples are immutable.
 This means that elements of a tuple cannot be changed once it has been
assigned.
>>> t1=(5,10,15,[50,90])
>>> t1[0]=100
TypeError: 'tuple' object does not support item assignment
But, if the element is itself a mutable datatype like list, its nested items can be
changed.
>>> t1[3][1]=100
>>> print(t1)
(5, 10, 15, [50, 100])
 Tuples are immutable which means you cannot add elements to
tuple
 Removing individual tuple elements is not possible.
 To explicitly remove an entire tuple, just use the del statement
>>> del t1
>>> t1
NameError: name 't1' is not defined
Description Python
Expression
Results
Concatenation (1, 2, 3) + (4, 5, 6) (1, 2, 3, 4, 5, 6)
Repetition ('Hi!',) * 4 ('Hi!', 'Hi!', 'Hi!', 'Hi!')
Membership 3 in (1, 2, 3) True
Iteration for x in (1, 2, 3):
print x,
1 2 3
Method Description
count(x)
Return the number of items that is equal
to x
index(x)
Return index of first item that is equal
to x
Function Description
all()
Return True if all elements of the tuple are true (or if the tuple is
empty).
any()
Return True if any element of the tuple is true. If the tuple is empty,
return False.
len() Return the length (the number of items) in the tuple.
max() Return the largest item in the tuple.
min() Return the smallest item in the tuple
sorted()
Take elements in the tuple and return a new sorted list (does not sort
the tuple itself).
sum() Return the sum of all elements in the tuple.
Method 1-using sorted() function
>>>t1=(95.5,25.8,2.6,10)
>>> t2=tuple(sorted(t1))
>>>print(t2)
(2.6, 10, 25.8, 95.5)
Method 2
Tuple does not contain sort() method. so to
sort tuple, it can be converted into list, then
sort the list, again convert the sorted list into
tuple
Program:
t1=(95.5,25.8,2.6,10)
print("Before Sortingn",t1)
L1=list(t1)
L1.sort()
t1=tuple(L1)
print("Before Sortingn",t1)
Output:
Before Sorting
(95.5, 25.8, 2.6, 10)
After Sorting
(2.6, 10, 25.8, 95.5)
 A tuple assignment can be used in for loop to traverse a list of tuples
Example:
Write a program to traverse tuples from a list:
>>>Students=[(1,"Aishwarya"),(2,"Mohanahari"),(3,"Dhivya")]
>>> for roll_no,name in students:
print(roll_no,name)
1 Aishwarya
2 Mohanahari
3 Dhivya
 Zip() is an inbuilt function in python.
 It takes items in sequence from a number of collections to make a list of tuples,
where each tuple contains one item from each collection.
 If the sequences are not of the same length then the result of zip() has the
length of the shorter sequence
Example:
>>> Items=['Laptop','Desktop','Mobile']
>>> Cost=[45000,35000,15000]
>>> Cost_of_items=tuple((list(zip(Items,Cost))))
>>> print(Cost_of_items)
(('Laptop', 45000), ('Desktop', 35000), ('Mobile', 15000))
 The * operator is used within zip function.
 The * operator unpacks a sequence into positional arguments.
>>> items_cost=(('Laptop', 45000), ('Desktop', 35000), ('Mobile', 15000))
>>> product,price=zip(*items_cost)
>>> print(product)
('Laptop', 'Desktop', 'Mobile')
>>> print(price)
(45000, 35000, 15000)
DICTIONARY
 Python dictionary is an collection of items.
 A dictionary has a key: value pair as elements
 Dictionaries are optimized to retrieve values when the key is known.
 Dictionaries are mutable
 Creating a dictionary is as simple as placing items inside curly braces {} separated by comma.
 An item has a key and the corresponding value expressed as a pair, key: value.
 values can be of any data type and can repeat,
 keys must be of immutable type (string, number or tuple with immutable elements) and must
be unique.
#empty dictionary
>>>D1={}
# all elements
>>> marks={'Sivapriya':90,‘Shruthi':95}
>>> print(marks)
{'Sivapriya': 90,‘Shruthi': 95}
# one element at a time
>>> m={}
>>> m['Mitun']=85
>>> print(m)
{'Mitun': 85}
#empty dictionary
>>>D1=dict()
#keys must be string
>>> m=dict(Sivapriya=90,Shruthi=95)
>>> print(m)
{'Sivapriya': 90, 'Shruthi': 95}
#another method (suitable for runtime input)
>>> marks=dict(((1,90),(2,95)))
>>> print(marks)
{1: 90, 2: 95}
Method 1- Method 2-using dict()
 Dictionary uses keys to access elements.
 Key can be used either inside square brackets or with the get()
method.
 When key is used with in square bracket, raises an Key error, if the
key is not found
 get() returns None, if the key is not found.
marks={'Sivapriya':90,'Shruthi':95}
>>> marks['Shruthi']
95
>>> marks['Mitun']
KeyError: 'Mitun'
>>> marks.get('Sivapriya')
90
>>> marks.get('Mitun')
>>>
 Dictionary are mutable.We can add new items or change the value of
existing items using assignment operator.
 If the key is already present, value gets updated, else a new key: value
pair is added to the dictionary.
Dictionary_name[key]=value
#change value
>>> marks['Shruthi']=100
>>> print(marks)
{'Sivapriya': 90, 'Shruthi': 100}
#To add new item
>>> marks['Mitun']=80
>>> print(marks)
{'Sivapriya': 90, 'Shruthi': 100, 'Mitun': 80}
my_dict = {'name':'Jack', 'age': 26}
# change value
my_dict['age'] = 27
print(my_dict)
{'name': 'Jack‘,'age': 27}
# add item
my_dict['address'] = ‘Coimbatore'
print(my_dict)
{'name': 'Jack‘, 'age': 27 ,'address':
‘Coimbatore'}
Example-2
#update() –updates elements from the another
dictionary object or from an iterable of key/value
pairs.
marks.update([('Mohamed',85),('Siddharth',70)])
>>> print(marks)
{'Sivapriya': 90, 'Shruthi': 100, 'Mitun': 80,
'Mohamed': 85, 'Siddharth': 70}
pop()-method removes as item with
the provided key and returns the
value.
marks={'Sivapriya':90, 'Shruthi': 100,
'Mitun': 80}
>>> marks.pop('Mitun')
80
>>> print(marks)
{'Sivapriya':90, 'Shruthi': 100}
popitem() can be used to remove and
return an arbitrary item (key, value) from
the dictionary(python 3-inserted order)
>>> marks.popitem()
('Shruthi', 100)
>>> print(marks)
{'Sivapriya':90}
Clear()-All the items can be
removed at once
>>> marks.clear()
>>> print(marks)
{}
del- keyword to remove individual items
or the entire dictionary itself.
marks={'Sivapriya':90, 'Shruthi': 100,
'Mitun': 80}
>>> del marks['Shruthi']
>>> print(marks)
{'Sivapriya':90, 'Mitun': 80}
>>> del marks
>>> print(marks)
NameError: name 'marks' is not defined
 A dictionary with in dictionary
#Creating nested dictionary
>>> players={"virat Kohli":{"ODI":7212,"Test":3245},"Sachin":{"ODI":18426,"Test":15921}}
>>> print(players)
{'virat Kohli': {'ODI': 7212, 'Test': 3245}, 'Sachin': {'ODI': 18426, 'Test': 15921}}
#Accessing
>>> print(players['virat Kohli'])
{'ODI': 7212, 'Test': 3245}
>>> print(players['Sachin']['Test'])
15921
Operation Example Output
Membership Test
Test if a key is in a
dictionary or not
Test for value
squares = {1: 1, 3: 9, 5: 25, 7: 49, 9: 81}
print(5 in squares)
print(25 in squares.values())
True
True
Iterating Through
a Dictionary
Iterate though each
key in a dictionary.
for i in squares:
print(i,end=‘,’)
for n,s in squares.items():
print(n,s)
1,3,5,7,9,
1 1
3 9
5 25
7 49
9 81
Nested
dictionary
for name,score in players.items():
print(name)
print(score)
for name,score in players.items():
print(name)
print("ODI=",score['ODI'])
print("Test=",score['Test'])
virat Kohli
{'ODI': 7212, 'Test': 3245}
Sachin
{'ODI': 18426, 'Test': 15921}
virat Kohli
ODI= 7212
Test= 3245
Sachin
ODI= 18426
Test= 15921
Method Description
clear() Remove all items form the dictionary.
copy() Return a shallow copy of the dictionary.
fromkeys(seq, v)
Return a new dictionary with keys from seq and value equal
to v (defaults to None).
get(key,d) Return the value of key. If key doesnot exit, return d(defaults to None).
items() Return a new view of the dictionary's items (key, value).
keys() Return a new view of the dictionary's keys.
pop(key,d)
Remove the item with key and return its value or d if key is not found.
If d is not provided and key is not found, raises KeyError.
popitem()
Remove and return an last item (key, value)(version 3.7). Return
arbitrary item in older python versions. Raises KeyError if it is empty.
setdefault(key,d)
If key is in the dictionary, return its value. If not, insert key with a value
of d and return d (defaults to None).
update([other])
Update the dictionary with the key/value pairs from other, overwriting
existing keys.
values() Return a new view of the dictionary's values
marks = {}.fromkeys(['Math','English','Science'], 0)
print(marks)
for item in marks.items():
print(item)
for key in marks.keys():
print(item)
for value in marks.values():
print(item)
Output:
{'English': 0, 'Science': 0, 'Math': 0}
('English', 0)
('Science',0)
('Math', 0)
English
Science
Math
0
0
0
Function Description
all()
Return True if all keys of the dictionary are true (or if the
dictionary is empty).
any()
Return True if any key of the dictionary is true. If the
dictionary is empty, return False.
len() Return the length (the number of items) in the dictionary.
sorted() Return a new sorted list of keys in the dictionary.
 Write a program to create phone directory using dictionary. Retrieve the contacts
and phone numbers as pair and also individually.
phonebook={"person1":878988949,"person2":986599566}
print("List of Contacts:")
for contacts in phonebook.items():
print(contacts)
print("Contact Names:")
for name in phonebook.keys():
print(name)
print("Mobile Numbers:")
for phone_no in phonebook.values():
print(phone_no)
Output:
List of Contacts:
('person1',
878988949)
('person2',
986599566)
Contact Names:
person1
person2
Mobile Numbers:
878988949
986599566
 Dictionary can be used to represent polynomial
 It is used to map a power to a coefficient
Representation of Polynomial
Consider, P(x) = 4x3 + 3x2+5x+1
Dictionary representation: P = {3:4,2:3,1:5,0:1}
Consider , P(x) = 9x7 + 3x4+5x
Dictionary representation: P = {7:9,4:3,1:5}
List can also be used to represent polynomial. But we have to fill in all zero
coefficients too since index must match power. Ex: 9x7 + 3x4+5x can be
represented in list as P=[9,0,0,3,0,0,5,0].
So dictionary can be used to represent polynomial, where we can specify only
non zero coefficients.
Write a Program to evaluate the polynomial P(x) = 4x3 + 3x2+5x+1
Program:
x=int(input("Enter x value"))
P={3:4,2:3,1:5,0:1}
result=0
for k,v in P.items():
result=result+(v*pow(x,k))
print(“The value of Polynomial P(x) = 4x^3+3x^2+5x+1 is:”, result)
Output:
Enter x value
2
The value of Polynomial P(x) = 4x^3+3x^2+5x+1 is : 55

Python tuples and Dictionary

  • 1.
  • 2.
  • 3.
    Tuples are sequences,just like lists. A tuple contains a sequence of items of any data type The difference between the tuple and list is that we cannot change the elements of a tuple once it is assigned whereas in a list, elements can be changed. Elements in the tuples are fixed Once it is created, we cannot add or remove elements Hence tuples are immutable
  • 4.
    Since, tuples arequite similar to lists, both of them are used in similar situations as well. However, there are certain advantages of implementing a tuple over a list. Tuples that contain immutable elements can be used as key for a dictionary.With list, this is not possible. If you have data that doesn't change, implementing it as tuple will guarantee that it remains write-protected.
  • 5.
     A tupleis created by placing all the items (elements) inside a parentheses (), separated by comma.  The parentheses are optional but is a good practice to write it.  A tuple can have any number of items and they may be of different types (integer, float, list, string etc.). # empty tule T1=() # tuples having of integers T2 = (1, 2, 3) # tuple with mixed datatypes T3 = (1, "Hello", 3.4) # nested tuple T4 = (“welcome", (8, 4, 6)) Method -1 Method-2 # empty tuple T1= tuple() # tuple function with string as arguments my_list = tuple(“welcome”) • Creating a tuple with one element is a bit tricky. • Single element should be followed by comma >>> T1=(4) >>> type(T1) <class 'int'> >>> T1=(4,) >>> type(T1) <class 'tuple'>
  • 6.
    we can accessthe elements of a tuple using index & slice operator Indexing  We can use the index operator [] to access an item in a tuple where the index starts from 0. >>> t1=(10,20,30) >>> print(t1[2]) 30 >>> print(t1[-3]) 10 Slicing  We can access a range of items in a tuple by using the slicing operator - colon ":“ >>>print(t1[0:2:1]) (10, 20) #nested tuple >>> t1=(10,20,(15,25)) >>> print(t1[2][0]) 15
  • 7.
     Unlike lists,tuples are immutable.  This means that elements of a tuple cannot be changed once it has been assigned. >>> t1=(5,10,15,[50,90]) >>> t1[0]=100 TypeError: 'tuple' object does not support item assignment But, if the element is itself a mutable datatype like list, its nested items can be changed. >>> t1[3][1]=100 >>> print(t1) (5, 10, 15, [50, 100])
  • 8.
     Tuples areimmutable which means you cannot add elements to tuple  Removing individual tuple elements is not possible.  To explicitly remove an entire tuple, just use the del statement >>> del t1 >>> t1 NameError: name 't1' is not defined
  • 9.
    Description Python Expression Results Concatenation (1,2, 3) + (4, 5, 6) (1, 2, 3, 4, 5, 6) Repetition ('Hi!',) * 4 ('Hi!', 'Hi!', 'Hi!', 'Hi!') Membership 3 in (1, 2, 3) True Iteration for x in (1, 2, 3): print x, 1 2 3
  • 10.
    Method Description count(x) Return thenumber of items that is equal to x index(x) Return index of first item that is equal to x
  • 11.
    Function Description all() Return Trueif all elements of the tuple are true (or if the tuple is empty). any() Return True if any element of the tuple is true. If the tuple is empty, return False. len() Return the length (the number of items) in the tuple. max() Return the largest item in the tuple. min() Return the smallest item in the tuple sorted() Take elements in the tuple and return a new sorted list (does not sort the tuple itself). sum() Return the sum of all elements in the tuple.
  • 12.
    Method 1-using sorted()function >>>t1=(95.5,25.8,2.6,10) >>> t2=tuple(sorted(t1)) >>>print(t2) (2.6, 10, 25.8, 95.5) Method 2 Tuple does not contain sort() method. so to sort tuple, it can be converted into list, then sort the list, again convert the sorted list into tuple Program: t1=(95.5,25.8,2.6,10) print("Before Sortingn",t1) L1=list(t1) L1.sort() t1=tuple(L1) print("Before Sortingn",t1) Output: Before Sorting (95.5, 25.8, 2.6, 10) After Sorting (2.6, 10, 25.8, 95.5)
  • 13.
     A tupleassignment can be used in for loop to traverse a list of tuples Example: Write a program to traverse tuples from a list: >>>Students=[(1,"Aishwarya"),(2,"Mohanahari"),(3,"Dhivya")] >>> for roll_no,name in students: print(roll_no,name) 1 Aishwarya 2 Mohanahari 3 Dhivya
  • 14.
     Zip() isan inbuilt function in python.  It takes items in sequence from a number of collections to make a list of tuples, where each tuple contains one item from each collection.  If the sequences are not of the same length then the result of zip() has the length of the shorter sequence Example: >>> Items=['Laptop','Desktop','Mobile'] >>> Cost=[45000,35000,15000] >>> Cost_of_items=tuple((list(zip(Items,Cost)))) >>> print(Cost_of_items) (('Laptop', 45000), ('Desktop', 35000), ('Mobile', 15000))
  • 15.
     The *operator is used within zip function.  The * operator unpacks a sequence into positional arguments. >>> items_cost=(('Laptop', 45000), ('Desktop', 35000), ('Mobile', 15000)) >>> product,price=zip(*items_cost) >>> print(product) ('Laptop', 'Desktop', 'Mobile') >>> print(price) (45000, 35000, 15000)
  • 16.
  • 17.
     Python dictionaryis an collection of items.  A dictionary has a key: value pair as elements  Dictionaries are optimized to retrieve values when the key is known.  Dictionaries are mutable
  • 18.
     Creating adictionary is as simple as placing items inside curly braces {} separated by comma.  An item has a key and the corresponding value expressed as a pair, key: value.  values can be of any data type and can repeat,  keys must be of immutable type (string, number or tuple with immutable elements) and must be unique. #empty dictionary >>>D1={} # all elements >>> marks={'Sivapriya':90,‘Shruthi':95} >>> print(marks) {'Sivapriya': 90,‘Shruthi': 95} # one element at a time >>> m={} >>> m['Mitun']=85 >>> print(m) {'Mitun': 85} #empty dictionary >>>D1=dict() #keys must be string >>> m=dict(Sivapriya=90,Shruthi=95) >>> print(m) {'Sivapriya': 90, 'Shruthi': 95} #another method (suitable for runtime input) >>> marks=dict(((1,90),(2,95))) >>> print(marks) {1: 90, 2: 95} Method 1- Method 2-using dict()
  • 19.
     Dictionary useskeys to access elements.  Key can be used either inside square brackets or with the get() method.  When key is used with in square bracket, raises an Key error, if the key is not found  get() returns None, if the key is not found. marks={'Sivapriya':90,'Shruthi':95} >>> marks['Shruthi'] 95 >>> marks['Mitun'] KeyError: 'Mitun' >>> marks.get('Sivapriya') 90 >>> marks.get('Mitun') >>>
  • 20.
     Dictionary aremutable.We can add new items or change the value of existing items using assignment operator.  If the key is already present, value gets updated, else a new key: value pair is added to the dictionary. Dictionary_name[key]=value #change value >>> marks['Shruthi']=100 >>> print(marks) {'Sivapriya': 90, 'Shruthi': 100} #To add new item >>> marks['Mitun']=80 >>> print(marks) {'Sivapriya': 90, 'Shruthi': 100, 'Mitun': 80} my_dict = {'name':'Jack', 'age': 26} # change value my_dict['age'] = 27 print(my_dict) {'name': 'Jack‘,'age': 27} # add item my_dict['address'] = ‘Coimbatore' print(my_dict) {'name': 'Jack‘, 'age': 27 ,'address': ‘Coimbatore'} Example-2 #update() –updates elements from the another dictionary object or from an iterable of key/value pairs. marks.update([('Mohamed',85),('Siddharth',70)]) >>> print(marks) {'Sivapriya': 90, 'Shruthi': 100, 'Mitun': 80, 'Mohamed': 85, 'Siddharth': 70}
  • 21.
    pop()-method removes asitem with the provided key and returns the value. marks={'Sivapriya':90, 'Shruthi': 100, 'Mitun': 80} >>> marks.pop('Mitun') 80 >>> print(marks) {'Sivapriya':90, 'Shruthi': 100} popitem() can be used to remove and return an arbitrary item (key, value) from the dictionary(python 3-inserted order) >>> marks.popitem() ('Shruthi', 100) >>> print(marks) {'Sivapriya':90} Clear()-All the items can be removed at once >>> marks.clear() >>> print(marks) {} del- keyword to remove individual items or the entire dictionary itself. marks={'Sivapriya':90, 'Shruthi': 100, 'Mitun': 80} >>> del marks['Shruthi'] >>> print(marks) {'Sivapriya':90, 'Mitun': 80} >>> del marks >>> print(marks) NameError: name 'marks' is not defined
  • 22.
     A dictionarywith in dictionary #Creating nested dictionary >>> players={"virat Kohli":{"ODI":7212,"Test":3245},"Sachin":{"ODI":18426,"Test":15921}} >>> print(players) {'virat Kohli': {'ODI': 7212, 'Test': 3245}, 'Sachin': {'ODI': 18426, 'Test': 15921}} #Accessing >>> print(players['virat Kohli']) {'ODI': 7212, 'Test': 3245} >>> print(players['Sachin']['Test']) 15921
  • 23.
    Operation Example Output MembershipTest Test if a key is in a dictionary or not Test for value squares = {1: 1, 3: 9, 5: 25, 7: 49, 9: 81} print(5 in squares) print(25 in squares.values()) True True Iterating Through a Dictionary Iterate though each key in a dictionary. for i in squares: print(i,end=‘,’) for n,s in squares.items(): print(n,s) 1,3,5,7,9, 1 1 3 9 5 25 7 49 9 81 Nested dictionary for name,score in players.items(): print(name) print(score) for name,score in players.items(): print(name) print("ODI=",score['ODI']) print("Test=",score['Test']) virat Kohli {'ODI': 7212, 'Test': 3245} Sachin {'ODI': 18426, 'Test': 15921} virat Kohli ODI= 7212 Test= 3245 Sachin ODI= 18426 Test= 15921
  • 24.
    Method Description clear() Removeall items form the dictionary. copy() Return a shallow copy of the dictionary. fromkeys(seq, v) Return a new dictionary with keys from seq and value equal to v (defaults to None). get(key,d) Return the value of key. If key doesnot exit, return d(defaults to None). items() Return a new view of the dictionary's items (key, value). keys() Return a new view of the dictionary's keys. pop(key,d) Remove the item with key and return its value or d if key is not found. If d is not provided and key is not found, raises KeyError. popitem() Remove and return an last item (key, value)(version 3.7). Return arbitrary item in older python versions. Raises KeyError if it is empty. setdefault(key,d) If key is in the dictionary, return its value. If not, insert key with a value of d and return d (defaults to None). update([other]) Update the dictionary with the key/value pairs from other, overwriting existing keys. values() Return a new view of the dictionary's values
  • 25.
    marks = {}.fromkeys(['Math','English','Science'],0) print(marks) for item in marks.items(): print(item) for key in marks.keys(): print(item) for value in marks.values(): print(item) Output: {'English': 0, 'Science': 0, 'Math': 0} ('English', 0) ('Science',0) ('Math', 0) English Science Math 0 0 0
  • 26.
    Function Description all() Return Trueif all keys of the dictionary are true (or if the dictionary is empty). any() Return True if any key of the dictionary is true. If the dictionary is empty, return False. len() Return the length (the number of items) in the dictionary. sorted() Return a new sorted list of keys in the dictionary.
  • 27.
     Write aprogram to create phone directory using dictionary. Retrieve the contacts and phone numbers as pair and also individually. phonebook={"person1":878988949,"person2":986599566} print("List of Contacts:") for contacts in phonebook.items(): print(contacts) print("Contact Names:") for name in phonebook.keys(): print(name) print("Mobile Numbers:") for phone_no in phonebook.values(): print(phone_no) Output: List of Contacts: ('person1', 878988949) ('person2', 986599566) Contact Names: person1 person2 Mobile Numbers: 878988949 986599566
  • 28.
     Dictionary canbe used to represent polynomial  It is used to map a power to a coefficient Representation of Polynomial Consider, P(x) = 4x3 + 3x2+5x+1 Dictionary representation: P = {3:4,2:3,1:5,0:1} Consider , P(x) = 9x7 + 3x4+5x Dictionary representation: P = {7:9,4:3,1:5} List can also be used to represent polynomial. But we have to fill in all zero coefficients too since index must match power. Ex: 9x7 + 3x4+5x can be represented in list as P=[9,0,0,3,0,0,5,0]. So dictionary can be used to represent polynomial, where we can specify only non zero coefficients.
  • 29.
    Write a Programto evaluate the polynomial P(x) = 4x3 + 3x2+5x+1 Program: x=int(input("Enter x value")) P={3:4,2:3,1:5,0:1} result=0 for k,v in P.items(): result=result+(v*pow(x,k)) print(“The value of Polynomial P(x) = 4x^3+3x^2+5x+1 is:”, result) Output: Enter x value 2 The value of Polynomial P(x) = 4x^3+3x^2+5x+1 is : 55