2

Say I have something like

import numpy as np
a = np.array([10,20,30,40,50,60])

# this will get the indices of elements in reverse sorted order
a.argsort()[::-1]

I can imagine that -1 specifies the direction, but what does the :: operator do? Is this a numpy thing or a python thing in general?

djvaroli
  • 1,223
  • 1
  • 11
  • 28

1 Answers1

3

It reverses the array:

In [149]: a = np.array([10,20,30,40,50,60])
In [150]: b = a[::-1]
In [151]: b
Out[151]: array([60, 50, 40, 30, 20, 10])

In detail the interpreter translates that indexing expression to:

In [152]: a.__getitem__(slice(None,None,-1))
Out[152]: array([60, 50, 40, 30, 20, 10])

Under the covers numpy just returns a view with an change in strides:

In [153]: a.strides
Out[153]: (8,)
In [154]: b.strides
Out[154]: (-8,)

That -1 slice step can be used elsewhere

To reverse strings and lists:

In [155]: 'astring'[::-1]
Out[155]: 'gnirtsa'
In [156]: [1,2,3,4][::-1]
Out[156]: [4, 3, 2, 1]

and to generate numbers in 'reverse' order:

In [157]: np.arange(0,10,1)
Out[157]: array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
In [158]: np.arange(9,-1,-1)
Out[158]: array([9, 8, 7, 6, 5, 4, 3, 2, 1, 0])
In [160]: np.arange(9,-1,-3)
Out[160]: array([9, 6, 3, 0])

Here we have to specify the end points, while in slicing those can be None, and taken from the object's shape.

hpaulj
  • 221,503
  • 14
  • 230
  • 353
  • Ok, I see. Thank you for the explanation, I've actually learned more from it than I was hoping to, so a big thanks! – djvaroli Mar 02 '21 at 21:08