Reputation: 31
I found some "mystery" problem when I'm trying filling list in "for in" loop.
Here is example:
>>> params = [1,2,3,4,5]
>>> el = {'param':0}
>>> el
{'param': 0}
>>> list = []
>>> for param in params:
... el['param'] = param
... list.append(el)
...
>>> print(list)
[{'param': 5}, {'param': 5}, {'param': 5}, {'param': 5}, {'param': 5}]
>>>
But I think result should be
>>> print(list)
[{'param': 1}, {'param': 2}, {'param': 3}, {'param': 4}, {'param': 5}]
>>>
How to resolve this problem? And why real result isn't similar with result in my mind?
Upvotes: 1
Views: 79
Reputation: 39853
You modify the same dict
in every iteration and add it to the list
. You'll get the other result when adding copies of this dict to the list
.
Just call list.append(dict(el))
instead.
Upvotes: 1
Reputation: 12214
You have one dict object that you are modifying. You add a reference to that one dict to your list multiple times. So your list contains 5 references to the same dict object.
Upvotes: 0
Reputation: 531185
el
refers to the same dictionary throughout, and list.append(el)
adds a reference to that dictionary, not a copy of its current value, to the list. You don't have a list of 5 different dictionaries, but a list of 5 references to one dictionary.
To see what is happening in closer detail, print list
and el
each time through the loop. You'll see a growing list that always refers to the current value of el
.
Upvotes: 2
Reputation: 20336
The problem is that you are using the same dictionary for each entry in your list. To fix this problem, add el = {}
above el['param'] = param
in your for loop.
Upvotes: 1
Reputation: 32511
Every element in your list contains a reference to the same dict. That is why you are seeing the same number in every element. Perhaps you want to do:
params = [1,2,3,4,5]
a = []
for param in params:
el = {'param': param}
a.append(el)
Also, be careful of shadowing builtins such as list
with your variable names.
Upvotes: 3