[Numpy-discussion] Help Understanding Indexing Behavior
Daniele Nicolodi
daniele at grinta.net
Tue Feb 25 20:01:16 EST 2014
On 26/02/2014 00:04, JB wrote:
> At the risk of igniting a flame war...can someone please help me understand
> the indexing behavior of NumPy? I will readily I admit I come from a Matlab
> background, but I appreciate the power of Python and am trying to learn more.
>
>>From a Matlab user's perspective, the behavior of indexing in NumPy seems
> very bizarre. For example, if I define an array:
>
> x = np.array([1,2,3,4,5,6,7,8,9,10])
>
> If I want the first 5 elements, what do I do? Well, I say to myself, Python
> is zero-based, whereas Matlab is one-based, so if I want the values 1 - 5,
> then I want to index 0 - 4. So I type: x[0:4]
The Python slicing syntax a:b defines the interval [a, b), while the
Matlab syntax defines the interval [a:b].
This post from Guido van Rossum (the creator of Python) explains the
choice of zero indexing and of this particular slice notation:
https://plus.google.com/115212051037621986145/posts/YTUxbXYZyfi
I actually find how Python works more straight forward: obtaining the
first n elements of array x is simply x[:n], and obtaining n elements
starting at index i is x[i:i+n].
Cheers,
Daniele
More information about the NumPy-Discussion
mailing list