This Python tutorial is part of our ongoing guide to programming in Python. While it is meant for beginning to intermediate developers, it can also be a handy reference for veteran programmers as well. In particular, we will be learning how to sort lists in Python using the sort() method, which is a list method used to sort lists specifically. We will also learn the sorted() function, which you can use to sort any type of iterable.
We have a lot to learn in this tutorial. Before we begin, however, you might want to refresh your memory regarding some of the basics of Python programming. If so, feel free to read or review these parts to our Python programming guide:
- How to Comment in Python
- Python Math Operators: Complete Guide
- Working with Python Logical Operators
- Python Best Practices for 2021
- How to Create and Print Lists in Python
- Accepting Input in Python with input()
- Overview of Regular Expressions and Regex in Python
What are Python Lists?
Python lists are ordered data structures that are made up of one or more elements that represent data or information. Each of these elements is placed between a pair of square brackets – or [ ] – and separated by commas. Python lists are mutable, meaning that the information inside of them can be changed.
In Python, we create a list in the following manner:
# Creating an empty list blank_list = [] # Creating a list with one string element single_list = ['Thanos'] # Creating a list with multiple string elements villains = ['Thanos', 'Doctor Doom', 'Kingpin'] # Create a list with a numeric value power_ranking = [100] # Creating a list with multiple number values total_power = [100, 80, 60] # Creating a list with multiple, mixed types of values mixed_list = [100, 'Thanos', 'Here is a sentence!'] # Lists can also have duplicate values duplicate_list = ['Thanos', 'Thanos', 'Thanos', 'Adam Warlock']
As stated, lists are made up of one or more elements. In this example:
villains = ['Thanos', 'Doctor Doom', 'Kingpin']
The first element is ‘Thanos, the second element is ‘Doctor Doom’, and ‘Kingpin’ is the third element. However, when we use or reference elements in a list, always remember that the first element starts at position ‘0’ and not position ‘1’ as you would expect. To access a particular element, we do so in the following manner:
# Creating a list villains = ['Thanos', 'Doctor Doom', 'Kingpin'] # printing the elements in a list print("The first element in our villains list is:",villains[0]) print("The second element in our villains list is:",villains[1]) print("The third element in our villains list is:",villains[2])
Sort Lists Using the sort() Method
In Python, there are two primary ways to sort a list. The first is known as the sort() method, which is a method that belongs specifically to lists and, as such, can only be used on lists. It is used to change the existing list by reordering its elements, versus actually creating a brand new list. Remember, lists are mutable – or changeable – and therefore there is no real need to create a brand new instance of a list when you can’t simply modify the order of the elements in the existing list.
When using the sort() method on a list, the default sort method sorts a list containing numeric values in order of their values. If you use sort() on a list of strings, that list will be sorted in alphabetical order by default. However, sort() does have two optional parameters you can use to change this default sorting behavior.
Before we delve into the optional sort() parameters, however, let’s take a look at some sample code showing how to sort Python lists using the sort() method:
# Sorting a list of numbers in Python with sort() power_level = [100, 90, 80, 50] print("The order of elements in power_level is: ",power_level) # The sort() method power_level.sort() print("The order of elements in power_level is now: ",power_level)
This code example creates a list called power_level and assigns it the values: 100, 90, 80, and 50. We then use the sort() method on our list, by appending .sort() to the end of our list. This causes the list to be sorted from lowest to highest value by default, which, in this instance, changes the order of our list. If you run this code in your code editor or IDE, you get the following result:
The order of elements in power_level is: [100, 90, 80, 50] The order of elements in power_level is now: [50, 80, 90, 100]
If we wanted to change the order of the list so that it is sorted by highest to lowest, we can use the reverse parameter. The reverse parameter uses a boolean value of either True or False, with False being the default setting. False tells Python to sort in ascending (lowest to highest) order, while True says to sort by descending (highest to lowest) order. Here is some code showing how to use the reverse parameter of the sort() method in Python:
# Sorting a list of numbers in Python with sort() power_level = [100, 90, 80, 50] print("The order of elements in power_level is: ",power_level) # The sort() method using reverse=True to sort descending power_level.sort(reverse=True) print("The order of elements in power_level is now: ",power_level) # The sort() method using reverse=False to sort ascending power_level.sort(reverse=False) print("The order of elements in power_level is now: ",power_level)
The output of this code, if you run it in your code editor, would be:
The order of elements in power_level is: [100, 90, 80, 50] The order of elements in power_level is now: [100, 90, 80, 50] The order of elements in power_level is now: [50, 80, 90, 100]
The second parameter we can set for sort() is the key parameter, which lets you create a custom sort. It is complicated to get hang of at first because it has so many options. In theory, you can use a plethora of different built-in Python functions to choose how a list will be sorted with the key parameter. For instance, you can use the len() function to sort by length. You can also create custom functions and call those within the key parameter to get your list to be sorted.
For example, you may be working with a list of numbers that are both positive and negative. If you wanted to sort those numbers by order of how far those numbers are from 0 – or the distance of that number from zero – you can use the abs() function within the key parameter. Here is how that looks in code:
# Sorting a list of numbers in Python with sort() power_level = [100, 90, -80, -50, 52, 84] print("The order of power_level is currently: ",power_level) # The sort() method using key=abs to sort by absolute value power_level.sort(key=abs) print("The order of elements in power_level is now: ",power_level)
Running this code snippet will create the following output:
The order of power_level is currently: [100, 90, -80, -50, 52, 84] The order of elements in power_level is now: [-50, 52, -80, 84, 90, 100]
Sorting String Values with sort() in Python
Sorting string values in Python with sort() works roughly the same as sorting numeric values, with some (probably) obvious differences. For instance, string values are sorted in alphabetical order versus their “value”. Here is how you can sort a list of string values in Python with the sorted() method:
# Sorting a list of stings in Python with sort() villains = ['Thanos', 'Doctor Doom', 'Molecule Man'] print("The order of villains is currently: ",villains) # The villains list sorted with sort() villains.sort() print("The order of elements in villains is now: ",villains)
Running this code results in the following:
The order of villains is currently: ['Thanos', 'Doctor Doom', 'Molecule Man'] The order of elements in villains is now: ['Doctor Doom', 'Molecule Man', 'Thanos']
By default, sort() sorts string values by alphabetical order from a-z. If we want to change this, again, we can use the reverse parameter. Remember, it accepts two boolean values: True and False. False will sort by order from a-z, while True will sort by z-a. Try running the following code in your code editor to see how this works:
# Sorting a list of stings in Python with sort() villains = ['Thanos', 'Doctor Doom', 'Molecule Man'] print("The order of villains is currently: ",villains) # The villains list sorted with sort() villains.sort(reverse=True) print("The order of elements in villains is now: ",villains) villains.sort(reverse=False) print("The order of elements in villains is now: ",villains)
The result of this code is:
The order of villains is currently: ['Thanos', 'Doctor Doom', 'Molecule Man'] The order of elements in villains is now: ['Thanos', 'Molecule Man', 'Doctor Doom'] The order of elements in villains is now: ['Doctor Doom', 'Molecule Man', 'Thanos']
As with numeric values, you can also use the sort() method to sort strings using the key parameter. For example, let’s say you wanted to sort your list of strings by order of length of each word in the list. We could use key with the len() function to do so. Check out this code example showing how this works:
# Sorting a list of stings in Python with sort() villains = ['Thanos', 'Doctor Doom', 'Molecule Man'] print("The order of villains is currently: ",villains) # The villains list sorted with sort() villains.sort(key=len) print("The order of elements in villains is now: ",villains) villains.sort(key=len, reverse=True) print("The order of elements in villains is now: ",villains)
Here is the result of running this code:
The order of villains is currently: ['Thanos', 'Doctor Doom', 'Molecule Man'] The order of elements in villains is now: ['Thanos', 'Doctor Doom', 'Molecule Man'] The order of elements in villains is now: ['Molecule Man', 'Doctor Doom', 'Thanos']
Sorting Python Lists with the sorted() Function
The other main way to sort lists in Python is by using the sorted() function. The main difference between the .sort() method and the sorted() function is that sorted() works on all iterables, which include lists, dictionaries, and tuples. The other difference is that sorted<() returns a brand new list and leaves the original list object unchanged.
Another important note: regardless of the type of iterable you pass to sorted(), it always returns a list. For instance, if you use sorted() on a tuple, a list will be returned. Below is a few examples of how to use the sorted() function in Python to sort lists and other iterables:
# Sorting a list of stings in Python with sorted() villains = ['Thanos', 'Doctor Doom', 'Molecule Man'] print("The order of villains is currently: ",villains) # The villains list sorted with sorted() villains_sorted = sorted(villains) print(villains_sorted) # Proof that villains is unchanged print("Villains remains unchanged: ",villains) # Another way to use sorted() print(sorted(villains)) # Proof, again, that villains is unchanged print(villains)
Here is the output of this code:
The order of villains is currently: ['Thanos', 'Doctor Doom', 'Molecule Man'] ['Doctor Doom', 'Molecule Man', 'Thanos'] Villains remains unchanged: ['Thanos', 'Doctor Doom', 'Molecule Man'] ['Doctor Doom', 'Molecule Man', 'Thanos'] ['Thanos', 'Doctor Doom', 'Molecule Man']
Finally, the sorted() function accepts three parameters, which include: the iterable you want to sort, the key, and reverse – the latter two of which work the same exact way they do with the sort() method. The iterable parameter would be the name of the iterable you wish to sort.