Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can someone explain the behaviour of empty dicts in python generator expressions? [duplicate]

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.

like image 219
sitaktif Avatar asked Sep 29 '22 13:09

sitaktif


1 Answers

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.

like image 80
Kevin Avatar answered Oct 06 '22 02:10

Kevin