Lists are one of the most important data types used in Python. We use python lists for various reasons. But sometimes these lists are mixed and we need to sort it. Here, we will learn Python List Sort. We use python sort () function to sort Python Lists alphabetically. The default behavior of this function is ascending (A to Z or Lower to higher value). We can also use it to sort as descending.
You can check all Python List Methods
In the below example, firstly, we will sort a list consist of different numbers.
The output of this Python List Sort code will be like below:
You can watch also the video of this lesson!
As you can see above, the list is sorted as ascending alphabetically. This is the default behaviour.
To sort a python list as descending, we will use reverse parameter of sort () method. The default behavior of this parameter is false, so the sort function sorts as ascending. To convert this as descending, we will set reverse parameter as True.
To do this, we will use the same list as above. This time we will also set reverese parameter as True.
The output list will be like below sorted as descending alphabetically.
We can use Python List Sort for also string lists. Some lists consist of different strings and if we sould like to sort this strings in the list, we can use python sort () function.
The output of this Python List Sort code will be like below. The strings are sorted as ascending.
If we have a string list consist of strings that begin with upper and lower cases, the sorting will be different because of the alphanumeric values location. For example, in the below example, you can see the sorted list that seems wrong if you think as case-insenstive.
The output of this List Sorting in Python will be:
To sort the list correctly as case-insenstive, we can use str.lower function as key function. ,
The output of this python code will be like below. The sort process will as case-insenstive.
There is also another way of reverse sorting. If you would like to sort your list reverse independant from the alphabet, you can do this with python reverse () function. In other words, python reverse method do not sort alphabetically, instead, it sorts the lists in reverse order.
As you can see below, the output of this python reverse function code will be:
Here, the sorting is as reverse of the list. This is not related about the location of the characters in the alphabet.
In this lesson, we have learned how to sort a python list with different Python List Sorting examples. You can use similar codes in your python codes for various purposes. List Sorting is an important function used in python coding. So, you will see different usages of these function during your career.