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': []}]
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With