This is a tutorial of the Python List sort() method. Learn to sort a Python List into Ascending or Descending order & using a particular key with examples.
Table of Contents
Python List sort()
Method
The sort()
method allows you to sort a given Python List in a given order. The order can be Ascending or Descending. This method also allows you to arrange given list items according to a particular key.
Syntax
You can directly apply the sort()
method on any Python List object as illustrated by the following syntax.
1 |
list.sort(key=keyFunction, reverse=True/False) |
sort()
Parameters
The Python List sort()
method can take two different arguments but both of these are optional to be provided. These are briefly defined below.
- key. The key Parameter is used to specify the key function according to which you want to sort the current list. We’ll find out more about this parameter in the examples section.
- reverse. This is a boolean type parameter which is set to False by default. It is used to specify the order in which you want to sort the list. If set to False, the given Python List will be sorted in ascending order and if set to False, then the list will be sorted into Descending order.
sort()
Return Value
sort()
method itself does not return any value. i.e. It returns None
.
Note. In case, you do just want to get the sorted list as a return value and do not want to shift the position of the elements in the original list, you can make use of the sorted()
function instead of the sort()
method.
Examples
I’ve provided below a few illustrative examples to demonstrate the use of the Python List sort()
method for different types of sorting operations.
Example 1. Sorting a List in Ascending Order
Most of the time we require our list just to be sorted in Ascending Order and that we can do like breeze with this method as depicted below.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
#A Python List #Containing Numbers in Random Order numbers = [9, 6, 2, 1, 3, 5] print("Random Numbers: ") #Sorting using sort() Method numbers.sort() #Printing sorted List print(numbers) #Python List Containing Strings names = ["Gurmeet", "Aman", "Deepinder", "Jaskaran"] #Sorting using sort() Method names.sort() print(names) |
Here we’re sorting two different lists in Ascending order. In the first list, we’ve some random integers that we’ve sorted into Ascending order using the sort()
method and similarly in the second case, we’ve sorted a list containing Name strings.
Example 2. Reverse Sort (Sorting Python List in Descending Order)
To Reverse Sort a list i.e. sorting the list in the Descending order, we just have to specify the argument reverse
of the method sort()
as True
as illustrated in the following example.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
#A Python List #Containing Numbers in Random Order numbers = [9, 6, 2, 1, 3, 5] print("Random Numbers: " + str(numbers)) #Reverse Sorting using sort() Method #Providing argument reverse = True numbers.sort(reverse = True) #Printing Reverse sorted List print(numbers) #Python List Containing Strings names = ["Gurmeet", "Aman", "Deepinder", "Jaskaran"] #Reverse Sorting using sort() Method #Providing argument reverse = True names.sort(reverse = True) print(names) |
The following output screenshot clearly shows that the two lists are now reverse sorted i.e. in descending order.
Sorting Lists using Key Parameter
As described earlier, the method sort()
also has a key parameter. We can provide a function as an argument for the key parameter to sort a given Python List according to our own logic. The logic according to which you want to sort a list has to be defined within a function and that function has to be provided as the argument for the key parameter.
Instead of defining your own logic functions, this function can also accept many built-in python functions as the key argument. Let’s say you want to sort a given list according to the length of the list items. The items with the shortest length should come first and the items with the largest string length should come at the end of the list. To achieve this kind of sorting, you just have to specify the argument key = len
as len()
is the Python’s built-in function to calculate the length of any Python object.
The proper syntax is defined below.
1 |
list.sort(key = len) |
The same sorting process can also be done using Python’s built-in function sorted()
as defined below.
1 |
sorted(list, key=len) |
The key parameter, therefore, opens a whole new set of sorting opportunities with the Python List.
Example 3. Sorting List using Key Argument & Built-in len()
Function
In this example, we have a list of some strings and each of these strings has a different length. So, here we’re sorting the list according to the length of the strings in ascending as well as in the descending order.
1 2 3 4 5 6 7 8 9 10 |
demo = ["aaaaa","aa","a","aaaaaa","aaaa","aaaaaaa","aaa"] print("Initial Ordeer: " + str(demo)) demo.sort(key = len) print("Small To Large: " + str(demo)) demo.sort(key = len, reverse = True) print("Large To Small: " + str(demo)) |
Example 4. Sorting is a Python List using Custom Logic
Here also we’ll make use fo the key argument but to this argument, we’ll provide our own defined custom function containing the logic of sorting.
I’ve taken a Python List that contains tuples as the items. Each tuple contains 3 numbers. The list is now sorted according to the ascending order of the sum of the numbers in each tuple item.
1 2 3 4 5 6 7 8 9 10 11 12 |
alist = [(12, 0, 9),(11, 1, 2), (12, 5, 3), (5, 3, 0), (3, 4, 8)] print("Original Order: " + str(alist)) def tupleSum(element): return sum(element) alist.sort(key = tupleSum) print("Ascending Order: " + str(alist)) alist.sort(key = tupleSum, reverse = True) print("Descending Order: " + str(alist)) |
I hope you found this guide useful. If so, do share it with others who are willing to learn Python and other programming languages. If you have any questions related to this article, feel free to ask us in the comments section.
And do not forget to subscribe to WTMatter!