4

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!

Peaceful
  • 4,920
  • 15
  • 54
  • 79
  • Possible duplicate of [this](http://stackoverflow.com/q/38834770/2285236) but I won't vote to be on the safe side. – ayhan Sep 06 '16 at 18:31
  • @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 Sep 06 '16 at 18:34
  • 1
    @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 Sep 06 '16 at 18:35
  • Beware of the `is` test with integers. `int('255') is 255` returns `True`, but the same for `257` does not. – hpaulj Sep 06 '16 at 19:41

1 Answers1

9

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.

user2357112
  • 260,549
  • 28
  • 431
  • 505