Reputation: 22887
How do you explain the following snippet where I get different results if I call id
on product
seperately, but the id
s are equal if I compare them against each other?
>>> from itertools import product
>>> id(product("01"))
41401800
>>> id(product(["0", "1"]))
41402080
>>> id(product("01")) == id(product(["0", "1"]))
True
Upvotes: 1
Views: 105
Reputation: 70705
It makes no difference whatsoever, but to explain it ;-): in your second spelling, both products are temporary objects, destroyed immediately after their id is obtained. "Immediately" is a consequence of CPython's reference counting. So the memory used for the first product is released before the second product is constructed, and that very same memory may get reused for the second product. There's no guarantee that it will be reused, or that it won't be. In your example, it so happened that it was reused.
Your first spelling could display this behavior too - but it so happens it didn't.
This isn't deep. It's trivial ;-)
BTW, it's less likely you'll get the same ids in the first spelling just because the interpreter has to allocate memory for other stuff between steps; for example, it needs to allocate memory to display "41401800".
Upvotes: 3