As far as I know, everything is object in Python and the id() should (am I right?) return a different number for each object.
In my case, id(1
Python can reuse memory positions.
When you run:
id(1.1)
you create a float value, ask for its id()
, and then Python deletes the value again because nothing refers to it. When you then create another float value, Python can reuse the same memory position and thus id(2.2)
is likely to return the same value for id()
:
>>> id(1.1)
140550721129024
>>> id(2.2)
140550721129024
Do this instead:
float_one, float_two = 1.1, 2.2
print id(float_one), id(float_two)
Now the float values have references to them (the two variables) and won't be destroyed, and they now have different memory positions and thus id()
values.
The reason you see different id()
values for small integers (from -5 through to 256) is because these values are interned; Python only creates one 1
integer object and re-uses it over and over again. As a result, these integers all have a unique memory address regardles, as the Python interpreter itself already refers to them, and won't delete them until the interpreter exits.
>>> id(1.1)
154154684
As 1.1 was not assigned to any variable so it is garbage collected and next time same id is going to be used for a float:
>>> id(2.2)
154154684
save 1.1 in a variable:
>>> f = 1.1
>>> id(f)
154154684 #this id is locked for now
Now new address is used:
>>> id(1.1)
154154700
>>> id(2.2)
154154700
This applies to integers as well:
>>> id(260)
154302180
>>> id(280)
154302180
Integers from -5
to 256
are actually cached in python, so they are always going to return different IDs.( "is" operator behaves unexpectedly with integers )
For strings:
Like integers some strings are also cached in python. So, id
of such strings is going to be different(For details read : 'is' operator behaves differently when comparing strings with spaces ):
>>> id('foo')
162861592
>>> id('foo')
162861568
Non-alphanumeric string(uses same id
):
>>> id('foo!&9((&')
162840000
>>> id('foo!&9((&')
162840000