id() and is operator

Chris Angelico rosuav at gmail.com
Sun Feb 22 14:23:53 EST 2015


On Mon, Feb 23, 2015 at 5:13 AM, Laura Creighton <lac at openend.se> wrote:
> In a message of Sun, 22 Feb 2015 09:53:33 -0800, LJ writes:
>>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. Now,
>>
>>>>> b[0] is b[2]
>>False
>
>
> You are running into one of the peculiarities of the python representation
> of numbers.  It can make things more efficient to represent all common
> numbers as 'there is only one' of them.

That shouldn't break the correspondence between id() and the is
operator. The id function is documented as returning an integer which
is "guaranteed to be unique among simultaneously existing objects",
and if all three elements of b exist through the entire duration of
this experiment, it should be perfectly safe to compare their id()s to
check object identity.

So the only explanation I can think of is: When you subscript a numpy
array, you aren't getting back a reference to a pre-existing object,
but you are instead getting a brand new object which is being created
for you. (This theory is supported by a vague recollection that
subscripting a numpy array returns a view of some sort, but you'd have
to check the docs.) If that theory is correct, then you'd expect to
find that the id() of such a thing is not stable; and that is, in
fact, what I see:

>>> import numpy as np
>>> b=np.array([[0]*2]*3)
>>> id(b[0])
26806960
>>> id(b[0])
26655344
>>> id(b[0])
26820432
>>> id(b[0])
26806960
>>> id(b[0])
26655344

After a few iterations, they're getting reused, but it's not like
playing with a Python list, where you would be getting back the exact
same object every time

You'd have to check the docs to be sure, but this is how I would go
about exploring the situation.

ChrisA



More information about the Python-list mailing list