Python The appended element in the list changes as its original variable changes

You are adding a reference to the dictionary to your list, then clear the dictionary itself. That removes the contents of the dictionary, so all references to that dictionary will show that it is now empty.

Compare that with creating two variables that point to the same dictionary:

>>> a = {'foo': 'bar'}
>>> b = a
>>> b
{'foo': 'bar'}
>>> a.clear()
>>> b
{}

Dictionaries are mutable; you change the object itself.

Create a new dictionary in the loop instead of clearing and reusing one:

list_ = []
for i in range(something):
    dict_ = {}
    get_values_into_dict(dict_)
    list_.append(dict_)
print list_

or better still, have get_values_into_dict() return a dictionary instead:

list_ = []
for i in range(something):
    dict_ = return_values_as_dict()
    list_.append(dict_)
print list_

Leave a Comment