Sorting Lists in Python. How to use sort() and sorted() to sort... | by Luay Matalka | Towards Data Science

In this tutorial, we will look at how to sort lists using sort() and sorted() based on different criteria in python.
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.
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.
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 num_list. 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 num_list.
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, absolute_value, 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 num_list 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).
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:
towardsdatascience.com
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
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)
towardsdatascience.com
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 num_list 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, num_list, 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, new_list. Note how num_list 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.
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_of_tuples 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 namesorted(list_of_tuples, key = name)# sort by agesorted(list_of_tuples, key = age)# sort by salarysorted(list_of_tuples, key = salary)
towardsdatascience.com
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.