4
votes

How do I explain the last line of these?

>>> a = 1
>>> a is a
True
>>> a = [1, 2, 3]
>>> a is a
True
>>> a = np.zeros(3)
>>> a
array([ 0.,  0.,  0.])
>>> a is a
True
>>> a[0] is a[0]
False

I always thought that everything is at least "is" that thing itself!

1
Possible duplicate of this but I won't vote to be on the safe side. - ayhan
@ayhan : I checked that link. The answer there seems to be saying the old thing that "is" checks the address locations etc. However, look at the second last of the code lines given above: If a is indeed a, then shouldn't so be all the elements of a? - Peaceful
@SnehalShekatkar: a[0] is just syntactic sugar for a.__getitem__(0); it's just another method call, which could (or could not) return anything in particular. - DSM
Beware of the is test with integers. int('255') is 255 returns True, but the same for 257 does not. - hpaulj

1 Answers

9
votes

NumPy doesn't store array elements as Python objects. If you try to access an individual element, NumPy has to create a new wrapper object to represent the element, and it has to do this every time you access the element. The wrapper objects from two accesses to a[0] are different objects, so a[0] is a[0] returns False.