Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

So here's the abstract code of what I'm trying to do in python.

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

Here when I clear the dict_, obviously the all the elements in the list_ are deleted as they're just address mapped to the variable dict_.

What, I want is to copy the instance of dict_ so that I can store it in the list_.

Can someone explain me a way to store the obtained dict in every loop into the list_? Thanks in advance.

like image 746
VoodooChild92 Avatar asked Jul 25 '26 02:07

VoodooChild92


1 Answers

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_
like image 119
Martijn Pieters Avatar answered Jul 27 '26 22:07

Martijn Pieters



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!