Skip to content

Sorting

The lists data structure has an associated sort method that orders items in descending order.

sample_lst = [4,5,3,-8,9,0]
sample_lst.sort() # Sort In-place
print(sample_lst)
[-8, 0, 3, 4, 5, 9]

Alternatively, sorting can be done using the sorted method which retuns a copy of the list in sorted order

sorted(sample_lst)
[-8, 0, 3, 4, 5, 9]

To change the order of the items in descending order, the reverse parameter can be used.

sorted(sample_lst, reverse=True)
[9, 5, 4, 3, 0, -8]

A function can also be applied to elements before they become sorted.

sorted(sample_lst, key=abs) # Assume each element is absolute before they are sorted.
[0, 3, 4, 5, -8, 9]