Like below, why does not the final r print [{'k': 1}, {'k': 2}] ?
l = [1, 2]
d = {}
r = []
for el in l:
d['k'] = el
print '> ' + str(d)
r.append(d)
print r
OUTPUT:
> {'k': 1}
> {'k': 2}
[{'k': 2}, {'k': 2}]
It is printed as wished before append operation, however after the dict is appended to a list, why does it append the last element repeatedly?
You’re assigning a new value to the same key when you pass through the loop a second time.
The first time through the loop,
elis1.d['k']is set to1, and then printed. Thendis appended tor.The second time through the loop,
elis2.d['k']— the very same value of the very same key of the very same dictionary — is set to2. Then the very same dictionary,d, is appended tor.Now
ris the same as if you had saidAnd since
d['k']is now2, both references todin the listryield{'k': 2}.If you want it to be different, you have to create a new dictionary every time through the loop.