Wednesday, March 28, 2018

How to sort list or numpy in descending order in Python??

Unfortunately, there seems not to be function which sort list or numpy in descending order.Therefore through this article, I'd like to share the way to sort list or numpy in descending order:)

list

There is two ways to sort in descending order.

In [1]: test_list = [3,2,4,8]

In [2]: test_list.sort()

In [3]: test_list
Out[3]: [2, 3, 4, 8]

In [4]: test_list.reverse()

In [5]: test_list
Out[5]: [8, 4, 3, 2]



In [1]: test_list = [3,2,4,8]

In [2]: test_list.sort()

In [3]: test_list[::-1]
Out[3]: [8, 4, 3, 2]

In [4]: test_list
Out[4]: [2, 3, 4, 8]

In [5]: 


Notice ! : First one is modify list in-place, however, Second one (slice) is to return new sorted list, hence original list stays as it is .

Incidentally, In terms of in-place or not, built-in method which is called "sorted" returns new sorted list, while "list.sort()" modify list in-place. In order to avoid confusion, "list.sort()" is to return None. The following is sample.

In [1]: test_list = [3,2,4,8]

In [2]: sorted(test_list)
Out[2]: [2, 3, 4, 8]

In [3]: test_list
Out[3]: [3, 2, 4, 8]

In [4]: 

numpy


I usually do as bellow.

In [1]: import numpy as np

In [2]: test_np = np.array([3,2,4,8])

In [3]: np.sort(test_np)[::-1]
Out[3]: array([8, 4, 3, 2])

Incidentally, sometimes we need sorted index of numpy. In that case, useful mehod "argsort" shoud be used as bellow.

In [4]: np.argsort(test_np)
Out[4]: array([1, 0, 2, 3])

In [5]: np.argsort(test_np)[::-1]
Out[5]: array([3, 2, 0, 1])

1 comment:

  1. You can do sorted(list, reverse=True). Those functions also have a ```key``` parameter to which you can pass custom functions so stuff gets sorted w.r.t. any order you specify.

    Best
    Nikolaj

    ReplyDelete