What happens behind the scenes when python adds small ints? [duplicate]

You’ve fallen into a not uncommon trap:

id(2 * x + y) == id(300 + x)

The two expressions 2 * x + y and 300 + x don’t have overlapping lifetimes. That means that Python can calculate the left hand side, take its id, and then free the integer before it calculates the right hand side. When CPython frees an integer it puts it on a list of freed integers and then re-uses it for a different integer the next time it needs one. So your ids match even when the result of the calculations are very different:

>>> x, y = 100, 40000
>>> id(2 * x + y) == id(300 + x)
True
>>> 2 * x + y, 300 + x
(40200, 400)

Leave a Comment