[Numpy-discussion] Question about bounds checking

Robert Kern robert.kern at gmail.com
Wed Aug 12 12:02:45 EDT 2009


On Mon, Aug 10, 2009 at 10:08, Rich E<rjel at ceh.ac.uk> wrote:
> Dear all,
> I am having a few issues with indexing in numpy and wondered if you could help
> me out.
> If I define an array
> a = zeros(( 4))
> a
> array([ 0.,  0.,  0.,  0.])
>
> Then I try and reference a point beyond the bounds of the array
>
> a[4]
> Traceback (most recent call last):
>  File "<stdin>", line 1, in <module>
> IndexError: index out of bounds
>
> but if I use the slicing format to reference the point I get
>
> a[0:4]
> array([ 0.,  0.,  0.,  0.])
> a[0:10]
> array([ 0.,  0.,  0.,  0.])

We do not raise an IndexError in the latter case because we follow
Python's behavior for lists and tuples.

In [1]: a = range(4)

In [2]: a[0:10]
Out[2]: [0, 1, 2, 3]

In [3]: a[9]
---------------------------------------------------------------------------
IndexError                                Traceback (most recent call last)

/Users/rkern/<ipython console> in <module>()

IndexError: list index out of range


This is particularly useful in cases where you are iterating over
chunks of the array. You do not have to handle the last chunk, which
may be smaller than the others, as a special case.

-- 
Robert Kern

"I have come to believe that the whole world is an enigma, a harmless
enigma that is made terrible by our own mad attempt to interpret it as
though it had an underlying truth."
  -- Umberto Eco



More information about the NumPy-Discussion mailing list