id() and is operator

Steven D'Aprano steve+comp.lang.python at pearwood.info
Sun Feb 22 20:31:25 EST 2015


LJ wrote:

> Hi everyone. Quick question here. Lets suppose if have the following numpy
> array:
> 
> b=np.array([[0]*2]*3)
> 
> and then:
> 
>>>> id(b[0])
> 45855552
>>>> id(b[1])
> 45857512
>>>> id(b[2])
> 45855552
> 
> Please correct me if I am wrong, but according to this b[2] and b[0] are
> the same object. 

Not necessarily. CPython (the version of Python you are using) can reuse
object IDs. This is not the case for all Pythons, e.g. Jython and
IronPython never reuse IDs. That means that if you compare the ID of two
objects in CPython which are not alive at the same time, they might have
received the same ID.

py> id("hello world")
3083591616
py> id("now what???")
3083591616

IDs are only unique if the objects are alive at the same time.

Numpy arrays are effectively C arrays of low-level machine values, what Java
calls "unboxed" values. So when you index a specific value, Python has to
create a new object to hold it. (In this case, that object is also an
array.) If that object is then garbage collected, the next time you ask for
the value at an index, the freshly created object may end up with the same
ID just by chance.

py> import numpy as np
py> b = np.array([[0]*2]*3)
py> x = b[0]
py> y = b[1]
py> print id(x), id(y)
155749968 156001664
py> print id(b[0]), id(b[1])  # temporary objects that are thrown away
156055016 156055016


If you try it yourself, you may or may not get exactly the same results. You
may need to print the IDs repeatedly until, just by chance, you end up with
identical IDs.



-- 
Steven




More information about the Python-list mailing list