Amelio Vazquez-Reina - 5 months ago 107

Python Question

I am surprised this specific question hasn't been asked before, but I really didn't find it on SO nor on the documentation of

`np.sort`

Say I have a random numpy array holding integers, e.g:

`> temp = np.random.randint(1,10, 10)`

> temp

array([2, 4, 7, 4, 2, 2, 7, 6, 4, 4])

If I sort it, I get ascending order by default:

`> np.sort(temp)`

array([2, 2, 2, 4, 4, 4, 4, 6, 7, 7])

but I want the solution to be sorted in

Now, I know I can always do:

`reverse_order = np.sort(temp)[::-1]`

but is this last statement

`np.sort`

Answer

`temp[::-1].sort()`

sorts the array in place, `np.sort(temp)[::-1]`

create a new array.

```
In [25]: temp = np.random.randint(1,10, 10)
In [26]: temp
Out[26]: array([5, 2, 7, 4, 4, 2, 8, 6, 4, 4])
In [27]: id(temp)
Out[27]: 139962713524944
In [28]: temp[::-1].sort()
In [29]: temp
Out[29]: array([8, 7, 6, 5, 4, 4, 4, 4, 2, 2])
In [30]: id(temp)
Out[30]: 139962713524944
```