Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Some strange behavior Python list and dict

Can anyone explain why this happened with list and how to clean list after appending 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': []}]
like image 527
kemmotar Avatar asked Dec 06 '22 08:12

kemmotar


1 Answers

That's a normal behaviour. Python uses references to store elements. When you do r.append(t) python will store t in r. If you modify t later, t in r will be also modified because it's the same object.

If you want to make t independant from the value stored in r you have to copy it. Look at the copy module.

like image 108
ibi0tux Avatar answered Jan 31 '23 09:01

ibi0tux