[SciPy-User] Array indexing question

Hanno Klemm klemm at phys.ethz.ch
Wed Apr 1 16:44:23 EDT 2015


> On 01 Apr 2015, at 22:07, jkhilmer at chemistry.montana.edu wrote:
> 
> 
> > 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.
>  
> Consider what range(5) does. Python lists also index in the same way.
> 
> 
> From  https://docs.python.org/2/tutorial/introduction.html:
> "One way to remember how slices work is to think of the indices as pointing between characters, with the left edge of the first character numbered 0. Then the right edge of the last character of a string of n characters has index n, for example:"
>  +---+---+---+---+---+---+
>  | P | y | t | h | o | n |
>  +---+---+---+---+---+---+
>  0   1   2   3   4   5   6
> -6  -5  -4  -3  -2  -1
> 
> 
> If you omit the colon, it's equivalent to a single character/item/row:  a[n] = a[n:n+1]
> Jonathan
> 


This is not entirely correct. the first form tends to yield the element, the second form a sequence:

In [1]: a=[1,2,3]

In [2]: a[1]
Out[2]: 2

In [3]: a[1:2]
Out[3]: [2]

In [5]: import numpy as np

In [6]: a = np.array([1,2,3])

In [7]: a[1]
Out[7]: 2

In [8]: a[1:2]
Out[8]: array([2])



Hanno




More information about the SciPy-User mailing list