Search code examples
pythonarraysnumpymatrix-indexing

Issue with understanding numpy array slicing


When slicing a Numpy array, it looks inconsistent to me.

In[87]: y
Out[87]: 
array([[1, 2, 3],
       [4, 5, 6],
       [7, 8, 9]])

In[88]: y[0,0]
Out[88]: 1

y[0,0] is 1. That's OK, but when I type

In[89]: y[0,0:1]
Out[89]: array([1])

Why is the slice [0,0:1] the single value array [1]? I was rather expecting array[1,4] which occurs when I type

In[90]: y[0,0:2]
Out[90]: array([1,4])

where I'd rather expect array[1,4,7] since y[0,2] is 7.

By the way, if of importance, I'm using Anaconda 2019 distro.

In[91]: import sys
   ...: print(sys.version)
3.7.3 (default, Mar 27 2019, 17:13:21) [MSC v.1915 64 bit (AMD64)]

Has anyone a clue why the slicing indexes look so confusing ? Thanks


Solution

  • Numpy uses the same slicing notation as Python does, i.e. [start:stop:step].

    As a convention, the value at index stop is excluded from the resulting sequence.

    You can find more information at paragraph 3 of this tutorial.

    The slice extends from the ‘from’ index and ends one item before the ‘to’ index.