简体   繁体   中英

Why is Python for loop returning last element in each pass?

My question title isn't quite correct but the code below should be clear enough.

instances = []
inst = {}
for i in range(4):
    print i
    inst['count'] = i
    instances.append(inst)
print instances

results in

0
1
2
3
[{'count': 3}, {'count': 3}, {'count': 3}, {'count': 3}]

I'm expecting

[{'count': 0}, {'count': 1}, {'count': 2}, {'count': 3}]

What am I not understanding?

Place the definition of the inst variable inside the loop.

instances = []
for i in range(4):
    inst = {}
    inst['count'] = i
    instances.append(inst)
print(instances)

As @Mario Ishac said the declaration of your dict is done before the for loop so you are working on the same dictionnary. Add it within your for loop. I have tested and that works.

instances = []
for i in range(4):
    inst = {}
    print(i)
    inst['count'] = i
    instances.append(inst)
print(instances)

So, what's happening here is that the dictionary you are trying to update is a runtime variable at this point, and every time it gets updated in the for loop, it is also updating the value of the item present in it so that the final output is the same where ever this variable is present. Considering values in both list and dict are not hardcoded values but dynamic in nature.

It can simply be fixed by creating an empty dict at every iteration. So it does not overwrite the same location in memory, and unique values are captured.

instances = []

for i in range(4):
    inst = {}
    print i
    inst['count'] = i
    instances.append(inst)
print instances

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM