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.
It isn't numpy, it's Python.
In Python, there are slices for sequence/iterable, which come in the following syntax
seq[start:stop:step] => a slice from start to stop, stepping step each time.
All the arguments are optional, but a :
has to be there for Python to recognize this as a slice.
Negative values, for step, also work to make a copy of the same sequence/iterable in reverse order:
>>> L = range(10)
>>> L[::-1]
[9, 8, 7, 6, 5, 4, 3, 2, 1, 0]
And numpy follows that "rule" like any good 3rd party library..
>>> a = numpy.array(range(10))
>>> a[::-1]
array([9, 8, 7, 6, 5, 4, 3, 2, 1, 0])
See this link
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 0
th element to the 5
th.
The slice doesn't include the 'endpoint' (named last element) so line 6 misses 0
when going backwards.
This isn't specific to numpy, the slice a[::-1]
is equivalent to slice(None, None, -1)
, where the first argument is the start index, the second argument is the end index, and the third argument is the step. None
for start or stop will have the same behavior as using the beginning or end of the sequence, and -1
for step will iterate over the sequence in reverse order.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With