Question

See example, why is there this difference between = and .extend:

d1=[1,2,3]
d2=[7,8,9]
d={1:d1,2:d2}

for key,value in d.items():
    value=['a','b','c']

output:{1: [1, 2, 3], 2: [7, 8, 9]}

for key,value in d.items():
    value.extend(['a','b','c'])

output:{1: [1, 2, 3, 'a', 'b', 'c'], 2: [7, 8, 9, 'a', 'b', 'c']}

.extend appears to have a write functionality that = doesn't. I would like to delve into why that is please.

Was it helpful?

Solution

Your first example rebinds value to a new list object. Because value is no longer associated with the dictionary value, the dictionary value is entirely unaffected.

The second example explicitly calls a method on the list object that alters the object in-place.

Python names are merely references to actual objects, as are dictionaries, lists, attributes, etc. If you point a name to something else (bind them to another object), all that happens to the previous object that was bound is that the reference count is decremented by 1. This can lead to the object being cleared from memory, but it won't change the value of the object.

But call a method on an object (such as value.extend()) then that method could affect the object. Since list objects are mutable, you'll see that change reflected everywhere that object is referenced.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top