i was just trying defaultdict and i am not able to understand as to why changing defaultdict (d[1]=2) causes change in the list v ,although appending has been done before the change in value. please help..
>>> d=defaultdict(int)
>>> d[1]=1
>>> d[2]=3
>>> v=[]
>>> v.append(d)
>>> v.append(d)
>>> v
[defaultdict(<type 'int'>, {1: 1, 2: 3}), defaultdict(<type 'int'>, {1: 1, 2: 3})]
>>> d[1]=2
>>> v
[defaultdict(<type 'int'>, {1: 2, 2: 3}), defaultdict(<type 'int'>, {1: 2, 2: 3})]
>>
Assignment statements in Python do not copy objects, they create bindings between a target and an object. For collections that are mutable or contain mutable items, a copy is sometimes needed so one can change one copy without changing the other.
Which means that you should append a shallow copy of d
to your list:
v.append(d.copy())