Skip to content
Advertisement

Reversed array in numpy?

Numpy tentative tutorial suggests that a[ : :-1] is a reversed a. Can someone explain me how we got there?

I understand that a[:] means for each element of a (with axis=0). Next : should denote the number of elements to skip (or period) from my understanding.

Advertisement

Answer

As others have noted, this is a python slicing technique, and numpy just follows suit. Hopefully this helps explain how it works:

The last bit is the stepsize. The 1 indicates to step by one element at a time, the - does that in reverse.

Blanks indicate the first and last, unless you have a negative stepsize, in which case they indicate last and first:

In [1]: import numpy as np

In [2]: a = np.arange(5)

In [3]: a
Out[3]: array([0, 1, 2, 3, 4])

In [4]: a[0:5:1]
Out[4]: array([0, 1, 2, 3, 4])

In [5]: a[0:5:-1]
Out[5]: array([], dtype=int64)

In [6]: a[5:0:-1]
Out[6]: array([4, 3, 2, 1])

In [7]: a[::-2]
Out[7]: array([4, 2, 0])

Line 5 gives an empty array since it tries to step backwards from the 0th element to the 5th.
The slice doesn’t include the ‘endpoint’ (named last element) so line 6 misses 0 when going backwards.

User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement