In Python, you can use the sort() method to sort a list in place. Or you can use the built-in sorted() function to get a sorted copy of the list. In this tutorial, you’ll learn:
Syntax of the sort() method and the sorted() functionCode examples of sorting lists in ascending and descending orderCustomize sort using the key parameterDifference between sort() vs sorted()
Let’s start!👩🏽💻
Syntax of Python sort() Method
The sort() method acts on a Python list. And it sorts the list in place—and modifies the original list. The syntax for Python’s sort() method is: Let’s now parse the above syntax.
is any valid Python list object.reverse is an optional parameter that takes either True or False. The default value of reverse is False, and the list is sorted in ascending order. Give True to sort the list in descending order.key is also an optional parameter that’s set to
In the next section, you’ll start coding simple examples.
How to Sort Python List in Ascending Order
Consider the list nums. To sort the list in ascending order, you can call the sort() method on the list. ▶ Run the following code snippet. The list nums has been sorted in ascending order, and the original list has been modified. This is called in-place sorting.
How to Sort Python List in Descending Order
To sort the list in descending order, set reverse to True, as shown below. You can see that the list is now sorted in descending order.
How to Use key with Python sort() Method
In this section, let’s use the key parameter and customize the sort. Here, mod5() is a function that takes in a number x, and returns the remainder when the number x is divided by 5. And we’d like to use the above function as the key. Now, run the following code cell. Take a minute to parse the output. Notice how instead of the regular sorting, you are now customizing your sort according to the key which is mod5.
The number that leaves the minimum remainder when divided by 5 comes first now. And the number that leaves the largest remainder when divided by 5 is the last element in the sorted list.
To verify this is the case, run the following code snippet. 5 divides 25 exactly, and the remainder is 0. So that’s the first element in the sorted list. 6 leaves a remainder 1, so it’s the second element, and so on. 9 leaves the remainder 4 when divided by 5, and it’s the last element in the sorted list. Now, let’s rewrite the above sort using the lambda expression, as shown below. So far, you’ve learned how to sort a list of numbers. Next, let’s see how you can sort a list of strings in Python.
How to Sort Python List in Alphabetical Order
In this section, you’ll learn to sort a list of strings—with examples inspired by Harry Potter. ✨ In our example, students is a list of students at Hogwarts. And we’d like to sort them in the alphabetical order of their names. When sorting a list of strings, the default sorting is in alphabetical order. Let’s print out the sorted list to verify the result of sorting.
How to Sort Python List in Reverse Alphabetical Order
In order to sort the list in reverse alphabetical order, set reverse = True, as shown in the code snippet below. From the output, you can see that the list has indeed been sorted in reverse order.
How to Use key Parameter Customize Sort
In this section, let’s customize the sort using the optional key parameter. Consider the following list, houses. Here, houses is a list of dictionaries. Each dictionary contains two key-value pairs, one denoting the students’ names and the other the house to which they belong. Now, we would like to sort this list houses in the alphabetical order of houses they belong to. As you might have guessed by now, we should set the key parameter to the house of the particular students. In order to retrieve the house of each student, you can define a function returnHouse(), as shown below. This function returns the house to which the particular student belongs. Now, you can call the sort() method on the houses list, as shown. In the output below, notice how the list is sorted by the house and not the students’ names. That’s why we have Gryffindor, Hufflepuff, and Slytherin—in alphabetical order. To define the key parameter accordingly, you could also use a lambda function. For every list item, this function returns the house for that list item. ▶ Run the following code cell to verify this. In all the examples so far, you’ve used the sort() method on a list. And you now know that it modifies the original list. What if you’d like to retain the original list as it is but obtain a sorted copy of the list? Well, in Python, you can use the sorted() function to do this.
Syntax of Python sorted() Function
The sorted() function takes in a list or any collection as the argument. And it returns a sorted copy of the list—and the original list is not modified. The syntax for Python’s sorted() function is: Notice how the syntax is very similar to the sort() method we saw earlier.
is any valid Python list object and is a required parameter.reverse and key are optional parameters
How to Sort Python List Using sorted() Function
#1. In this example, nums is a list of numbers. You can call the sorted() function with nums as the argument. And assign it to the list sorted_nums1. In the output above, you can see that nums has been sorted in ascending order by default. Also, notice that the original list nums is not modified—because sorted() returns a new list. This is verified below. #2. Now, set the optional parameter reverse to True and get sorted_nums2. As shown in the code cell below, sorted_nums2 is a new list with the items sorted in the descending order. #3. In this example, let’s work with a list of strings. As with the previous examples, calling the sorted() function returns a new list. And the items are sorted in alphabetical order. #4. Now, let’s customize the sort using the optional key parameter. Set the key to len. This will sort the list based on the length of the strings. The string with the shortest length appears first in the sorted list, and the longest string appears at the end of the sorted list. In the output above, pear is the shortest string, and strawberry is the longest string.
Python sort() Method vs. sorted() Function
So far, you’ve learned how to use the sort() method as well as the sorted() function. In this section, let’s enumerate the differences between these two methods.
Summing Up 👩🏫
I hope you found this Python lists tutorial helpful. Let’s quickly summarize what we’ve covered.
Use list.sort(reverse = True | False, key =
Now that you’ve learned how to sort Python lists, learn about list comprehension in Python. Or you could as well learn how to handle files or work with JSON files in Python. You may try the examples given above in the Geekflare Online Python Compiler.