id() and is operator

Laura Creighton lac at openend.se
Sun Feb 22 13:13:31 EST 2015


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.

So.

  Python 2.7.9 (default, Dec 11 2014, 08:58:12)
 [GCC 4.9.2] on linux2
 Type "help", "copyright", "credits" or "license" for more information.
 >>> a = 1
 >>> b = 1
 >>> a is b
 True
 >>> a = 1001
 >>> b = 1001
 >>> a is b
 False

--------
Don't rely on this.  Other implementations are free to implement this
however they like.
--------

[PyPy 2.4.0 with GCC 4.9.2] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>>> a = 1001
>>>> b = 1001
>>>> a is b
True

Laura





More information about the Python-list mailing list