[Numpy-discussion] Help Understanding Indexing Behavior
jslavin at cfa.harvard.edu
Wed Feb 26 08:32:17 EST 2014
This behavior is a property of python slicing. It takes some getting used
to, but has its advantages. In general in a slice [i:j] the indices go
from i to j-1. In the case that i is 0 it's easy to think of it as j
giving the number of elements (by the way you can also do a[:j] -- i.e.
leaving out the 0 -- and get the same result. Maybe someone else could
provide more background on why slicing is defined the way it is in python,
but in the end you just have to get used to it.
On Tue, Feb 25, 2014 at 6:07 PM, <numpy-discussion-request at scipy.org> wrote:
> From: JB <jonathan.j.buck at gmail.com>
> To: numpy-discussion at scipy.org
> Date: Tue, 25 Feb 2014 23:04:26 +0000 (UTC)
> Subject: [Numpy-discussion] Help Understanding Indexing Behavior
> 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
> >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]
> And get in return: array([1, 2, 3, 4]). So I got the first value of my
> array, but I did not get the 5th value of the array. So the "start" index
> needs to be zero-based, but the "end" index needs to be one-based. Or to
> it another way, if I type x and x[0:4], the 4 means different things
> depending on which set of brackets you're looking at!
> It's hard for me to see this as anything by extremely confusing. Can
> explain this more clearly. Feel free to post links if you'd like. I know
> this has been discussed ad nauseam online; I just haven't found any of the
> explanations satisfactory (or sufficiently clear, at any rate).
Jonathan D. Slavin Harvard-Smithsonian CfA
jslavin at cfa.harvard.edu 60 Garden Street, MS 83
phone: (617) 496-7981 Cambridge, MA 02138-1516
fax: (617) 496-7577 USA
-------------- next part --------------
An HTML attachment was scrubbed...
More information about the NumPy-Discussion