Some weird Python list and dict behavior

Can someone explain why this happened to the list and how to clear the list after adding to another list?

>>> t = {} >>> t["m"] = [] >>> t {'m': []} >>> t["m"].append('qweasdasd aweter') >>> t["m"].append('asdasdaf ghghdhj') >>> t {'m': ['qweasdasd aweter', 'asdasdaf ghghdhj']} >>> r = [] >>> r.append(t) >>> r [{'m': ['qweasdasd aweter', 'asdasdaf ghghdhj']}] >>> t["m"] = [] >>> r [{'m': []}] 
+4
source share
5 answers

This is normal behavior. Python uses references to storage items. When you execute r.append(t) , python will store t in r . If you change t later, t in r will also be changed, because it is the same object.

If you want to make t independent of the value stored in r , you need to copy it. Take a look at the copy module.

+10
source

When you call r.append(t) , you say: "Save the reference to the value stored in t at the end of the r list." The dictionary t not copied, so when you change t you change the data referenced by r .

This can be seen more clearly:

 >>> x = [] >>> y = x >>> x.append(1) >>> y [1] 

This sets y value referenced by x , so when x changes, it appears that y also changes.

+2
source

Dictionaries change in Python, take a copy instead

 >>> import copy >>> r.append(copy.copy(t)) >>> t {'m': ['qweasdasd aweter', 'asdasdaf ghghdhj']} >>> r [{'m': ['qweasdasd aweter', 'asdasdaf ghghdhj']}] >>> t["m"]=None >>> r [{'m': ['qweasdasd aweter', 'asdasdaf ghghdhj']}] 
+1
source

You can try:

 import copy r.append(copy.deepcopy(t)) 

and that should work.

Greetings

+1
source

This is normal. When you assign an object to a variable, python will not copy this object to your variable. It will simply assign the link of the source object to your new object.

 In [1]: a = [1,2] In [2]: b = a In [3]: a.remove(1) In [4]: b Out[4]: [2] 

Here b will only contain a link to the original list a. If you want to override this behavior, you can use the copy module.

 In [7]: import copy In [8]: a = [1,2] In [9]: b = copy.deepcopy(a) In [10]: a.remove(1) In [11]: b Out[11]: [1, 2] 

deepcopy duplicates everything, including individual elements.

+1
source

All Articles