pouard Tintin
pouard Tintin

Reputation: 9

Strange Bug : List.append in Python erasing precedent input and cloning the new one instead each

Ok I have been working many times with list in python and it s the first time I encounter this problem : Near the strange place I've got this ( simplified )

list = []
dict = {}
things = {'1':'Am', '2':'I', '3':'Dumb?'}
[...]

for key,value in things.items():
    if value:
        dict[key]=value

        print(dict)
        list.append(dict)
        print(list)

And get the this result :

{'1':'Am'}
[{'1':'Am'}]
{'2':'I'}
[{'2':'I'},{'2':'I'}]
{'3':'Dumb?'}
[{'3':'Dumb?'},{'3':'Dumb?'},{'3':'Dumb?'}]

hinhin, someone have ever get this ? I, m stuck, thank iou :)

Upvotes: 0

Views: 57

Answers (1)

willeM_ Van Onsem
willeM_ Van Onsem

Reputation: 476659

This is not a bug. You simply add the same dictionary multiple times to the list. As a result if you manipulate that dictionary, you see the changes in all elements of the list, since these all refer to the same dictionary.

You should create a new dictionary each iteration, for example with:

result = []
things = {'1':'Am', '2':'I', '3':'Dumb?'}

for key, value in things.items():
    if value:
        result.append({key: value})
    print(list)

Or with simple list comprehension:

result = [{k: v} for k, v in things.items() if v]

Upvotes: 1

Related Questions