id() and is operator

Terry Reedy tjreedy at udel.edu
Mon Feb 23 01:14:03 EST 2015


On 2/22/2015 12:53 PM, 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,

You are, as other explained
 > but according to this b[2] and b[0] are the same object.
>>>> b[0] is b[2]
> False
>
> Any clarification is much appreciated.

In Python, 'two' objects can only be the same thing if they exist 
simultaneously.  Retry your experiment with simultaneous objects.

 >>> b0 = b[0]
 >>> b1 = b[1]
 >>> b2 = b[2]  # etc.

The three objects will have different ids.  The mail purpose of the id 
function is to text properties of a particular implementation.  It also 
has uses with ctypes.  Beginners should generally ignore it, and 
certainly not touch it until reading and understanding its doc.  The 
main use for 'is' is for 'is None' comparison.

-- 
Terry Jan Reedy




More information about the Python-list mailing list