The world’s leading publication for data science, AI, and ML professionals.

Sorting Lists in Python

How to use sort() and sorted() to sort lists in python

Photo by Markus Spiske on Unsplash
Photo by Markus Spiske on Unsplash

In this tutorial, we will look at how to sort lists using sort() and sorted() based on different criteria in python.


Sorting a List

There are two ways to sort a list. We can either use the sort() method or the sorted() function. The sort() method is a list method and thus can only be used on lists. The sorted() function works on any iterable.

sort() method

The sort() method is a list method that modifies the list in-place and returns None. In other words, the sort() method modifies or changes the list it is called on, and does not create a new list.

The sort() method has two optional parameters: the key parameter and reverse parameter. The key parameter takes in a function that takes a single argument and returns a key to use for sorting. By default, the sort() method will sort a list of numbers by their values and a list of strings alphabetically. The reverse parameter accepts a boolean value of True or False. The default value for reverse is False, meaning it sorts in ascending order. To sort in descending order, we would set reverse=True. These parameters will make much more sense as we look at some examples below.

Sorting a List of Numbers

Let’s say that we have a list of numbers and we want to sort it in ascending order.

num_list = [1,-5,3,-9,25,10]
num_list.sort()
print(num_list)
# [-9,-5,1,3,10,25]

So we have a list of numbers, or _numlist. We call the sort() method on this list. Notice how we didn’t pass in a value for the key parameter. Thus, it just sorted this list of numbers by their actual values. And since we didn’t set reverse = True, it sorted in ascending order. The sort() method modified our _numlist.

What if we want to sort our list based on the absolute values of the numbers? That is when we would need to use the key parameter. The key parameter takes in a function that takes a single argument and returns a key to use for sorting.

num_list = [1,-5,3,-9,25,10]
def absolute_value(num):
    return abs(num)
num_list.sort(key = absolute_value)
print(num_list) 
# [1,3,-5,-9,10,25]

We defined a function, _absolutevalue, that takes in a number and returns its absolute value. We then passed this function in as the argument for the key parameter of the sort() method. Thus, it runs each element or number of _numlist through the absolute value function before it makes the comparison. As a result, the absolute values of the numbers are used to sort this list in ascending order (since reverse is set to False by default).

Using a lambda expression

We could have passed in a lambda expression instead for the key parameter as follows:

num_list.sort(key = lambda num: abs(num))

For more information about lambda functions:

Lambda Expressions in Python


Remember that the sort() method returns None. Thus, if we set the output, or return value, of the sort() method to a new variable, we get None as follows:

new_list = num_list.sort(key = absolute_value)
print(new_list)
# None

Using built-in functions

Instead of writing our own absolute_value function as we did above, we could have just passed in the python built-in abs() function for the key parameter as follows:

num_list.sort(key = abs)

Unpacking Operators in Python


sorted() function

The sorted() function can accept three parameters: the iterable, the key, and reverse. In other words, the sort() method only works on lists, but the sorted() function can work on any iterable, such as lists, tuples, dictionaries, and others. However, unlike the sort() method which returns None and modifies the original list, the sorted() function returns a new list while leaving the original object unchanged.

Let’s sort _numlist again using the absolute values but using the sorted() function instead:

num_list = [1,-5,3,-9,25,10]
new_list = sorted(num_list, key = abs)
print(new_list) 
# [1,3,-5,-9,10,25]
print(num_list)
# [1,-5,3,-9,25,10]

We pass in the iterable, _numlist, to the sorted() function, along with the built-in abs function to the key parameter. We set the output of the sorted() function to a new variable, _newlist. Note how _numlist is unaltered since the sorted() function does not modify the iterable it acts on.

Note: No matter what iterable is passed in to the sorted() function, it always returns a list.

Sorting a List of Tuples

Let’s say that we have a list of tuples. Each element of the list is a tuple that contains three elements: the name, age, and salary.

list_of_tuples = [
    ('john', 27, 45000),
    ('jane', 25, 65000),
    ('beth', 31, 70000)
]

We can sort this list alphabetically, by age, or by salary. We can specify which we want to use with the key parameter.

To sort by age, we can use the following code:

sorted_age_list = sorted(list_of_tuples, key = lambda person: person[1])
print(sorted_age_list) 
# [('jane', 25, 65000), ('john', 27, 45000), ('beth', 31, 70000)]

Each element of the _list_oftuples is passed in to the lambda function as the person parameter. The element at index 1 of each tuple is returned. That is the value that is used to sort the list, which is the age.

To sort the name alphabetically, we can do so without passing a key at all since by default the first element of each tuple is what is compared (and remember, by default, strings are sorted alphabetically):

sorted_name_list = sorted(list_of_tuples)
print(sorted_name_list) 
# [('beth', 31, 70000), ('jane', 25, 65000), ('john', 27, 45000)]

However, we can specify that we want to sort by the first element of each tuple as follows:

sorted_name_list = sorted(list_of_tuples, key = lambda person: person[0])
print(sorted_name_list) 
# [('beth', 31, 70000), ('jane', 25, 65000), ('john', 27, 45000)]

Remember that we can assign a lambda expression to a variable (similar to using the def keyword to define a function). Thus, we can organize the lambda expressions based on the criteria they use to sort the list:

name = lambda person: person[0]
age = lambda person: person[1]
salary = lambda person: person[2]
# sort by name
sorted(list_of_tuples, key = name)
# sort by age
sorted(list_of_tuples, key = age)
# sort by salary
sorted(list_of_tuples, key = salary)

Sorting a Dictionary in Python


If you enjoy reading stories like these and want to support me as a writer, consider signing up to become a Medium member. It’s $5 a month, giving you unlimited access to stories on Medium. If you sign up using my link, I’ll earn a small commission.

Join Medium with my referral link – Luay Matalka


Conclusion

In this tutorial, we compared the sort() method and sorted() function when sorting a list based on different criteria. We learned how the sort() method modifies the original list, and the sorted() function returns a new list.


Related Articles