[Numpy-discussion] Help Understanding Indexing Behavior
Chris Barker
chris.barker at noaa.gov
Wed Feb 26 13:50:16 EST 2014
On Wed, Feb 26, 2014 at 5:32 AM, Slavin, Jonathan
<jslavin at cfa.harvard.edu>wrote:
> This behavior is a property of python slicing. It takes some getting used
> to, but has its advantages.
>
quite a few, actually!
They key with slicing is to think of the index as pointing to the space
between the elements:
0 1 2 3 4 5
| | | | | |
but the reason (and beauty) of this is that it results in a number of nifty
properties:
len( seq [i:j] ) == j-i
seq[i:j] + seq[j:k] == seq[i:k]
len( seq[:i] ) == i
len( seq[-i:] ) == i
and if you have an array representing a axis, for instance, and want to
know the value of a given index:
x = x_0 + i*dx
or the index of a given value:
i = (x - x_0) / dx
Notice that I don't have a single +1 or -1 in all of that -- this make sit
easier to undersand and a lot less error prone.
-Chris
--
Christopher Barker, Ph.D.
Oceanographer
Emergency Response Division
NOAA/NOS/OR&R (206) 526-6959 voice
7600 Sand Point Way NE (206) 526-6329 fax
Seattle, WA 98115 (206) 526-6317 main reception
Chris.Barker at noaa.gov
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/numpy-discussion/attachments/20140226/87ab6b4e/attachment.html>
More information about the NumPy-Discussion
mailing list