Some friends and I were discussing things related to memory management in Python when we stumbled upon the behaviour below:
In [46]: l = ({} for _ in range(6))
In [47]: [ id(i) for i in l]
Out[47]:
[4371243648, # A
4371245048, # B
4371243648, # A
4371245048, # B
4371243648, # etc.
4371245048]
What is surprising here is that we don't seem to have well defined behaviours: the dict is neither a new one each time nor the same reference each time.
On top of that, we got this weird behaviour (not code was run in the interpreter between these two snippets).
In [48]: m = ({} for _ in range(6))
In [49]: [ id(i) for i in m]
Out[49]:
[4371154376, # C
4371245048, # B (same B as above!)
4371154376, # C
4371245048, # B
4371154376,
4371245048]
Can anyone explain this behaviour? Using list comprehensions (l = [{} for _ in range(6)]
) shows different addresses for each dict.
The dictionaries are being destroyed as soon as they are no longer referenced by the generator. You are comparing the ID's of dead objects, and ID's can be reused.
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