Python List sort() method

Python List sort method

Now, we are going to have a look at the sort method. As the name suggests, with the help of the sort method, we would be able to sort the list, in ascending order or descending order.

So, whenever we need to sort our list in either ascending order or descending order, we can make use of the sort method. Let’s have a look at a simple program, which tries to demonstrate the same thing.

Python List Sort Method

As you can see in the above program, we have a list, which has some numbers, and then we are trying to use the sort method on the list. If you look at the output of the above program, you can simply see that the list is sorted in ascending order. Let’s have a look at the output –

[4, 5, 22, 29, 31, 39, 42]

As you can see, the list is sorted in the ascending order. If you want to sort the list in descending order, then we need to give an optional argument to the sort method, which is reverse. When the reverse is set to True, the list will be sorted in ascending order. Let’s have a look at this as well.

As you can see, we have the reverse set to True, and due to this, the list will be sorted in descending order. Let’s have a look at the output for the above program now –

[42, 39, 31, 29, 22, 5, 4]

So, whenever we want to sort our list, we can make use of the sort method on the list. Remember that this method returns None, instead it sorts the original list. So, we would use this sort method for the list, as and when required in our Python programs.