+ 1

Dictionaries

Please help to state simple example for mutable and immutable object and its concept in python dictionaries. I am not clear enough by reading the lessons and comments.

13th Aug 2019, 3:11 PM
May Thazin Nyein
May Thazin Nyein - avatar
1 Respuesta
+ 3
Mutable list example: a = [1, 2, 3] b = [4, 5, a] print(a) #[1, 2, 3] print(b) #[4, 5, [1, 2, 3]] If you change a, you also changed b[2], and if you changed b[2], you also changed a, that's because b[2] is a, not just a copy of a, Python avoids copies. b[2].append(6) print(a) #[1, 2, 3, 6] print(b) #[4, 5, [1, 2, 3, 6]] Then what if you used a as a key in a dictionary? If dictionaries supported mutable objects as keys: d = {[1, 2, 3]: "klm", a: "nop"} print(d) #{[1, 2, 3]: "klm", [1, 2, 3, 6]: "nop"} If you changed a again: a.pop() print(a) #[1, 2, 3] print(d) #{[1, 2, 3]: "klm", [1, 2, 3]: "nop"} Now there would be 2 duplicate dictionary keys. print(d[[1, 2, 3]]) #So would this print "klm" or "nop"?
13th Aug 2019, 3:29 PM
Seb TheS
Seb TheS - avatar