Immediate re-use of id
Python use the same id
for all objects you create:
>>> for x in range(10):
print(id([1, 2]))
4479841736
4479841736
4479841736
4479841736
4479841736
4479841736
4479841736
4479841736
4479841736
4479841736
Because there is no reference to the created list, it will be garbage collected immediately and the id
will be re-used.
Using the same name repeatedly
Assigning the list to a name obj
, will keep the lists alive until a new list is assigned to the same name:
>>> for x in range(10):
obj = [1, 2]
print(id(obj))
4486925128
4486925192
4486925128
4486925192
4486925128
4486925192
4486925128
4486925192
4486925128
4486925192
In the second iteration obj
exists and obj = [1, 2]
creates new lists first before assigning to obj
. Once assigned, the old list will be garbage collected and the id
becomes available again for re-use. Repeat this for each following iteration.
Keeping a reference
When you keep a reference in a list to all created lists:
>>> objs = []
>>> for x in range(10):
obj = [1, 2]
print(id(obj))
objs.append(obj)
4480011848
4483963144
4486916488
4486914376
4486914568
4486916616
4486914824
4486915016
4486915272
4486915464
Python has to use different id
s for all of them.
Interpreter effects
Working at the standard interactive prompt (Python 3.5.1), I can produce this:
>>> id([1, 2])
4330529608
>>> id([1, 2])
4330529608
>>> id([1, 2])
4330529608
>>> id([1, 2])
4330529608
>>> id([1, 2])
4330529608
>>> id([1, 2])
4330529608
But working in IPython or an IPython Notebook, you get this:
In [1]: id([1, 2])
Out[1]: 4359684552
In [2]: id([1, 2])
Out[2]: 4379935816
In [3]: id([1, 2])
Out[3]: 4373482696
In [4]: id([1, 2])
Out[4]: 4359674248
In [5]: id([1, 2])
Out[5]: 4373482696
This due to the fact that IPython is doing some more work in background and creates objects that re-use the freed id
before you can create your new object.