How do you sort a Python list alphabetically?
There are two easy ways to sort a list in Python: using the standard
function or using the
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
to change all values within the list to a
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
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
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
function does not mutate (change) the original iterable passed in.
>>> print(months) ['January', 'February', 'March', 'April', 'May']
Notice how the variable
still contains the same order.
If you needed to change the original list in-place then you can use the list method
, like so:
>>> months.sort() >>> print(months) ['April', 'February', 'January', 'March', 'May']
And just like the
function you can apply the parameter
to reverse the order of the list:
>>> months.sort(reverse=True) >>> print(months) ['May', 'March', 'January', 'February', 'April']
Just as the
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,
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
forloop. 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
In Python, one way to sort a list alphabetically is by using the built-in
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.
Function With Lists
To alphabetically sort a list using the
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']
Another way to sort a list alphabetically is by using the
method. Unlike the
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.
method With Lists
To use the
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
function keeps the original list untouched, whereas the
list method does modify the original list.
Sometimes, you may want to sort a list based on specific criteria.
In such cases, you can use a parameter labelled
, which is available in both the
function and the
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
method cannot handle data of a different type. To prevent this error from occurring you can apply a
function in the
Change Data Types In List With
To prevent a
from occurring on the mixed list and to treat all the values in a similar way you can use a
function to change the value of each item to then apply the
Here’s how this would work using the same above example that gave the
>>> 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
data type, but due to the
parameter associated with a
function that passes through each element in the list as
and then returns the element as a
This means the sort function
the values through the
parameter, applies the changes
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
To sort a list using custom criteria, pass a function that takes a single argument and returns a value used for sorting as the
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']
function calculates the length of each string and sorts the list of strings from smallest to largest.
Another popular application of the
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
function that passes in the
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.
function and the
method provide a simple and effective way to sort lists in reverse order using the
parameter. By setting the
, the list gets sorted in
By default, the reverse parameter is set to
, which means the list will be sorted in
Here’s an example using the
function (the approach is the same using the
>>> 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
function or the built-in list method
. The only difference between both approaches is that the
function produces a new list, whereas the
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
Forgetting to use the
keyparameter 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 the
sort()method modifies the list in-place, while the
sorted()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:
sorted()function when you want to create a new sorted list without modifying the original list. On the other hand, use the
sort()method when you intend to sort the list in-place.
Use the key parameter with the
sorted()function or the
sort()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.