How do you sort a Python list alphabetically?
There are two easy ways to sort a list in Python: using the standard
sorted()
function or using the
.sort()
list method.
Assuming you have a list of strings you can apply either method to sort the list alphabetically. If you have a list of numbers and strings you can use the parameter
key
to change all values within the list to a
str
data type and then perform the necessary sort (
more on that later
).
Here is a quick demonstration of how you can do this with a string already containing strings:
>>> months = ['January', 'February', 'March', 'April', 'May']
>>> sorted(months)
['April', 'February', 'January', 'March', 'May']
As you can see from the above result the
sorted()
function takes an iterable, such as a list, and then outputs an ordered list. If you wanted to sort the list the other way you could simply add the parameter with value
reverse=True
to the function and you would get an alphabetical list in the order from Z to A.
>>> sorted(months, reverse=True)
['May', 'March', 'January', 'February', 'April']
One other important thing to notice is that the
sorted()
function does not mutate (change) the original iterable passed in.
>>> print(months)
['January', 'February', 'March', 'April', 'May']
Notice how the variable
months
still contains the same order.
If you needed to change the original list in-place then you can use the list method
.sort()
, like so:
>>> months.sort()
>>> print(months)
['April', 'February', 'January', 'March', 'May']
And just like the
sorted()
function you can apply the parameter
reverse=True
to reverse the order of the list:
>>> months.sort(reverse=True)
>>> print(months)
['May', 'March', 'January', 'February', 'April']
Just as the
sorted()
function similarly done this list method also performs the same operation, but applies the change to the list variable used.
If this has been too fast for you, I’ll go through each of the above demonstrations with the two means slowly.
Python List Basics
Python lists are a type of data structure that allows you to store multiple items in a single variable. They are flexible, mutable, and ordered collections of elements enclosed in square brackets
[]
.
Each element in a list can be accessed using its index, which starts from zero.
Create A Python list
To create a list in Python, you simply need to assign a variable to a series of items enclosed in square brackets. The items can be of various types, such as strings, integers, or floating-point numbers. You can also mix different data types within a single list. Here’s an example of creating a list:
my_list = ['apple', 'banana', 'cherry']
Python List Examples
Python lists are versatile and have many practical uses. You can use them to store and manipulate collections of data. Here are a few examples of common operations with lists:
-
Accessing an item in a list:
To retrieve an item from a list, use its index position inside square brackets. For example,
my_list[0]
returns ‘apple’. -
Adding an item to a list:
To append an item to an existing list, use the
append()
method. For example,my_list.append('orange')
adds ‘orange’ to the end of the list. -
Removing an item from a list:
To remove an item from a list, use the
remove()
method by passing the element’s value. For example,my_list.remove('banana')
removes ‘banana’ from the list. -
Iterating through a list:
You can loop through the items in a list, by using a
for
loop. The code for looping through a list would look something like this:
>>> months = ['January', 'February', 'March', 'April', 'May']
>>> for x in months:
... print(x)
...
January
February
March
April
May
Alphabetising Python Lists
sorted()
Function
In Python, one way to sort a list alphabetically is by using the built-in
sorted()
function. The
sorted()
function takes a list as an input and returns a new list containing the sorted elements of the original list.
This function does not modify the original list, which is helpful in cases when you want to preserve the initial order of the elements.
sorted()
Function With Lists
To alphabetically sort a list using the
sorted()
function, simply pass the list as an argument:
>>> unsorted_list = ['cherry', 'apple', 'banana', 'kiwi', 'orange']
>>> sorted_list = sorted(unsorted_list)
>>> print(sorted_list)
['apple', 'banana', 'cherry', 'kiwi', 'orange']
sort()
List Method
Another way to sort a list alphabetically is by using the
sort()
method. Unlike the
sorted()
function, the
sort()
method sorts the original list in-place, meaning that the order of the elements in the original list is changed. This method does not return a new list.
sort()
method With Lists
To use the
sort()
method with a list, simply call the method on the list:
>>> unsorted_list = ['cherry', 'apple', 'banana', 'kiwi', 'orange']
>>> unsorted_list.sort()
>>> print(unsorted_list)
['apple', 'banana', 'cherry', 'kiwi', 'orange']
As you can see from both outputs the result is exactly the same, however, the sorted list from using the
sorted()
function keeps the original list untouched, whereas the
.sort()
list method does modify the original list.
key
Parameter
Sometimes, you may want to sort a list based on specific criteria.
In such cases, you can use a parameter labelled
key
, which is available in both the
sorted()
function and the
.sort()
list method.
The
key
parameter allows you to specify a custom function for determining the sorting order.
This can be helpful when items within your list are of a different data type and you want to treat them all as the same data type. For example, if there are strings and numbers in your list.
>>> years = ['2023', 2022, '2025', 2020]
>>> sorted(years)
TypeError: '<' not supported between instances of 'int' and 'str'
As you can see from the above output the
sorted()
method cannot handle data of a different type. To prevent this error from occurring you can apply a
lambda
function in the
key
parameter.
Change Data Types In List With
key
Parameter
To prevent a
TypeError
from occurring on the mixed list and to treat all the values in a similar way you can use a
lambda
function to change the value of each item to then apply the
sort
needed.
Here’s how this would work using the same above example that gave the
TypeError
:
>>> years = ['2023', 2022, '2025', 2020]
>>> sorted(years, key=lambda x: str(x))
[2020, 2022, '2023', '2025']
Notice the result of the sort keeps all elements within the list as their original
int
data type, but due to the
key
parameter associated with a
lambda
function that passes through each element in the list as
x
and then returns the element as a
str
.
This means the sort function
first applies
the values through the
key
parameter, applies the changes
then
sorts the items.
Besides applying the same conversion of type to each element, you can also perform different types of sorting on each element. Here is another application:
Custom Sort With
key
Parameter
To sort a list using custom criteria, pass a function that takes a single argument and returns a value used for sorting as the
key
parameter. In this example I will sort each element according to the length of the string:
>>> unsorted_list = ['apple', 'banana', 'kiwi', 'orange']
>>> sorted_list = sorted(unsorted_list, key=lambda x: len(x))
>>> print(sorted_list)
['kiwi', 'apple', 'banana', 'orange']
The
len()
function calculates the length of each string and sorts the list of strings from smallest to largest.
Another popular application of the
key
parameter is when sorting a list of strings where different cases are found at the start of each string.
Sorting Lists of Strings With Different Cases
Another common problem when sorting a list alphabetically is that some strings start with capital letters with others not capitalised.
Here’s a demonstration of the problem:
>>> surnames = ['de Angelo', 'De Suza', 'Deloitte']
>>> sorted(surnames)
['De Suza', 'Deloitte', 'de Angelo']
As you can see sorting these names places the capitalised names to not be in the correct order.
To combat this issue with your alphabetical sorting you can apply a
lambda
function that passes in the
str
function
.lower()
such that each element in the list is
converted to lower string
.
>>> surnames = ['de Angelo', 'De Suza', 'Deloitte']
>>> sorted(surnames, key=lambda x: x.lower())
['de Angelo', 'De Suza', 'Deloitte']
I have found this technique very useful when sorting names, as some names can contain lowercase words.
Sorting Lists in Reverse Order
In some situations, you might need to sort a list in descending order, also known as reverse alphabetical sorting. This comes in handy when you have a specific requirement to display list elements in a specific manner.
Use
reverse
Parameter
Both the
sorted()
function and the
.sort()
method provide a simple and effective way to sort lists in reverse order using the
reverse
parameter. By setting the
reverse
parameter to
True
, the list gets sorted in
descending order
.
By default, the reverse parameter is set to
False
, which means the list will be sorted in
ascending order
.
Here’s an example using the
sorted()
function (the approach is the same using the
.sort()
list method):
>>> animals = ["kangaroo", "platypus", "koala", "wombat"]
>>> sorted_animals = sorted(animals, reverse=True)
>>> print(sorted_animals)
['wombat', 'platypus', 'koala', 'kangaroo']
Sorting List Alphabetically In Python: Summary
Sorting a list in Python can quickly be done using either the
sorted()
function or the built-in list method
.sort()
. The only difference between both approaches is that the
sorted()
function produces a new list, whereas the
.sort()
method mutates the list being performed on.
When sorting a list alphabetically, be mindful of the common pitfalls you might face when sorting lists in Python. These mistakes include:
-
Trying to sort lists containing incompatible data types, leading to
TypeError
. -
Forgetting to use the
key
parameter when sorting strings with different cases or when trying to sort a list based on a specific attribute. -
Modifying the original list unintentionally when using the
sort()
method. Remember that thesort()
method modifies the list in-place, while thesorted()
function returns a new sorted list.
To make your list sorting more efficient and less error-prone, it’s essential to follow these best practices:
-
Use the
sorted()
function when you want to create a new sorted list without modifying the original list. On the other hand, use thesort()
method when you intend to sort the list in-place. -
Use the key parameter with the
sorted()
function or thesort()
method when dealing with lists of mixed-case strings or when you want to sort based on specific attributes. - Use meaningful variable names when defining custom sorting functions for better readability and ease of understanding.
- Consider using custom sorting functions in combination with the key parameter for more complex sorting scenarios, such as sorting based on multiple attributes or rules.
If you have any problems trying to sort your list, you can explore some common issues and how to troubleshoot them .