CBSE Class 11 Computer Science Question 78 of 112

Dictionaries — Question 18

Back to all questions
18
Question

Question 18

Discuss the working of copy( ) if

(i) the values are of immutable types,

(ii) the values are of mutable types.

Answer

(i) the values are of immutable types
If the values are of immutable types then any changes made in the copy created with copy( ) will not be reflected in the original dictionary.
For example:

d1 = {1:'Neha' , 2: 'Saima' , 3: 'Avnit' , 4: 'Ana'}
d2 = d1.copy()
d2[5] = 'Taru'
print(d2)
print(d1)
Output
{1: 'Neha', 2: 'Saima', 3: 'Avnit', 4: 'Ana', 5: 'Taru'} 
{1: 'Neha', 2: 'Saima', 3: 'Avnit', 4: 'Ana'} 

(ii) the values are of mutable types
If the values are of mutable types then any changes made in the copy created with copy() will be reflected in the original dictionary.
For example:

d1 = {1:[1,2,3] , 2: [3,4,5]}
d2 = d1.copy()
d2[1].append(4)
print(d2)
print(d1)
Output
{1: [1, 2, 3, 4], 2: [3, 4, 5]}
{1: [1, 2, 3, 4], 2: [3, 4, 5]}