Computer Science
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]}
Related Questions
What do you understand by shallow copy of a dictionary ?
What is the use of copy( ) function ?
Which of the following will result in an error for a given valid dictionary D?
- D + 3
- D * 3
- D + {3 : "3"}
- D.update( {3 : "3"})
- D.update { {"3" : 3}}
- D.update("3" : 3)
The following code is giving some error. Find out the error and correct it.
d1 = {"a" : 1, 1 : "a", [1, "a"] : "two"}