In this article, we would cover how to sort and reverse sort in Python. Perform the following operations on a list. For the same, we would use built-in list.sort() method.
If we want sort lists in place then, we use list.sort() method. When we talk of sorting lists in place, it means the original list gets modified and the elements in the list are sorted. Or, we can say it doesn’t create a new copy of the list. And, it sorts the original list itself. list.sort() returns with None.
sort a list
Understand it with the help of couple of examples. Let’s say we have a list x,
x=[7,11,89,4,2,65,111]
Use sort() method to sort the list –
x.sort()
To see the order of elements in the list –
x
It would return with –
[2, 4, 7, 11, 65, 89, 111]
Clearly, we have the list sorted. But, notice something we didn’t specify the order in which elements are to be sorted. list.sort() by default sorts the list in an ascending order. Now, what if we have to sort the list in a descending order. That is something which we are about to discuss next.
reverse sort a list
Continuing with the above example –
x=[7,11,89,4,2,65,111]
use reverse parameter to sort the list in descending order –
x.sort(reverse=True)
to check if we have got the required list –
x
This would return with –
[111, 89, 65, 11, 7, 4, 2]
Here, notice that we have use parameter reverse. By default, the reverse is set to False. So, we don’t have to specifically mention reverse=False while sorting the list in an ascending order. But, we need to pass the parameter as True when we do the opposite (i.e. sorting list in descending order).
In conclusion, we have covered how to sort and reverse sort in Python with the help of couple of examples. In coming articles, we would cover sorted() method and difference between sort() and sorted().