# Fix Python – Efficiently sorting a numpy array in descending order?

## 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 descending order.

Now, I know I can always do:

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

but is this last statement efficient? Doesn’t it create a copy in ascending order, and then reverses this copy to get the result in reversed order? If this is indeed the case, is there an efficient alternative? It doesn’t look like `np.sort` accepts parameters to change the sign of the comparisons in the sort operation to get things in reverse order.

Now we will see solution for issue: Efficiently sorting a numpy array in descending order?

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

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

In : temp
Out: array([5, 2, 7, 4, 4, 2, 8, 6, 4, 4])

In : id(temp)
Out: 139962713524944

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

In : temp
Out: array([8, 7, 6, 5, 4, 4, 4, 4, 2, 2])

In : id(temp)
Out: 139962713524944
``````