[SciPy-User] Array indexing question

Sturla Molden sturla.molden at gmail.com
Wed Apr 1 15:20:36 EDT 2015


"Joseph C Slater, PhD, PE" <joseph.slater at wright.edu> wrote:
> On http://wiki.scipy.org/NumPy_for_Matlab_Users, under Linear Algebra
> Equivalents, the following row is given:
> a(1:5,:)     a[0:5] or a[:5] or a[0:5,:]      the first five rows of a
> 
> I'm quite confused as I thought since the first row is indexed as zero,
> the fifth would be as 5. Indeed, a[5,5] provides the value in the 6th row
> and 6th column. However, it seems that 0:5 means 0, 1, 2, 3, 4 . So, when
> used with a colon, the 5 no longer means the same value as when used
> without. Am I missing something? Why this peculiar behavior, and how does
> one avoid errors with this inconsistency? (What's the logic to help me
> understand why it works this way?)


Consider what range(5) does. Python lists also index in the same way.

In C we have this too: for(i=0; i<5; i++)

The logic is this: To get n elements starting from i, we take a[i:i+n]. We
also have the nice symmetry a[:n] and a[n:]. BDFL Guido van Rossum decided
that this is how Python objects should index. So that's what NumPy does
too. 


Sturla




More information about the SciPy-User mailing list