Last Updated:

Sorting in Python

Sorting in Python

The sort method is very important in the Python programming language and cannot be bypassed, as it is the foundation in your further study of Python. This method is very useful, has a bunch of features and interesting details, which we will consider in this article.

Purpose and use cases

 

Using the sort() method, you can sort the list into:

  • Ascending order
  • Descending order

This method is used to sort the list in place, which means that it mutates it or modifies it directly without creating additional copies. Because of this, you should only use this method if:

  1. You want to change (sort) the list permanently.
  2. You don't need to save the original version of the list.

If this suits your needs, then the .sort() method is exactly what you're looking for.

Syntax and arguments

 

Let's see how you can call .sort() to make the most of it. This is the simplest call (without arguments):

<list>.sort()

If you do not pass any arguments, then by default:

  • The list will be sorted in ascending order.
  • List items will be compared directly by using their values using the < operator.

For example:

>>f = [7, 4, 7, 5, 8, 4, 10]
>>>f.sort()
>>>f
[7, 4, 7, 5, 8, 4, 10] # Understood!

Custom Arguments

 

To customize how the sort() method works, you can pass two optional arguments:

  • key
  • reverse

Let's see how they change the behavior of this method. Here we have a method call with these two arguments:

<list>.sort(key=<f>,reverse=<f>)

Before explaining how they work, I would like to explain that you, in a method call, parameter names must be included before their respective values, for example:

key=<f>
reverse=<value>

This is because they are arguments only for keywords. If you pass a custom value to them, their names must be specified in a method call followed by an equal sign = and their corresponding values, for example:

<list>.sort(key=<f>,reverse=<value>)

TypeError: sort() does not accept positional arguments

Reverse

 

Now that you know what keyword-only arguments are, let's turn to reverse. The reverse value can be either true or false:

  • False means that the list will be sorted in ascending order.
  • True means that the list will be sorted in descending order (reverse).

by default reverse is false

# List of integers
>>>f = [7, 4, 7, 5, 8, 4, 10]
>>>f.sort()
>>>f
[4, 4,5,7, 7, 8, 10]
# List of strings
>>>r = ["B", "Q", "W", "E", "R"]
>>>r.sort()
>>>r
['B', 'E', 'R', 'Q', 'W']

As you can see, the list of letters is sorted alphabetically. To specify that it is reverse-correct, the list must be sorted in descending order (reverse).

# List of integers
>>>f = [7, 4, 7, 5, 8, 4, 10]
>>>f.sort()
>>>f
[10, 9, 8, 7.7, 5,4, ] #
List of strings
>>> c = ["B", "Q", "W", "E", "R"]
>>>r.sort(reverse=True)
>>>r
['W', 'Q', 'R', 'E', 'B']

Here, as you can see, the list of letters is sorted in reverse order due to the reverse method.

True

Now that you know how to work with the inverse parameter, let's look at the key parameter.

Key value:

None, this means that the list items will be compared directly. For example, in a list of integers, the integers themselves can be used for comparison. A single-argument function that generates an intermediate value for each element. This intermediate value is calculated only once and is used for comparison throughout the sorting process.

We use this when we don't want to compare elements directly, such as when we want to compare strings based on their length (an intermediate value).

For example:

Let's say we want to sort a list of rows by their length, from the shortest line to the longest. We can pass the function len as the key value, for example:

>> d = [«ddd», «ee», «r»]
>>>d.sort(key=len)
>>>d
[‘r’, ‘ee’, ‘ddd’]

Tip: Note that we only pass the function name (len) without parentheses because we are not calling the function. This is very important.

Note the difference between directly comparing elements and comparing their lengths (Using the default key (None) value, we'd sort the strings alphabetically (left), but now we're sorting them by length (right).

What happens behind the scenes? Each element is passed as an argument to the len() function, and the value returned by this function call is used to perform comparisons during the sorting process. The result is a list with a different sort criterion, which is length.

Here's another example:

Another interesting example is sorting a list of strings as if they were all written in lowercase letters (for example, making "Aa" equivalent to "aa"). According to the lexicographical order, capital letters precede lowercase letters:

>> «E» < «e»

Thus, the line "Olga" will stand in front of "Olga" in the sorted list, even if their lowercase versions are in the opposite order:

>> "Olya" < "Olga"
True
>>> "olya" < "olga"
False

To avoid the distinction between uppercase and lowercase letters, we can pass the str.lower function as a key. This will create a lowercase version of the strings that will be used for comparison:

>> e = [“Olya”, “Olga”, “Anya”, “Sonya”]
>>>e.sort(key=str.lower)
>>>e
[“Anya”, “Olga”, “Olya”, “Sonya”]

Notice that now "Olga" stands in front of "Olga" in the sorted list, which is exactly what we wanted.

Tip: If we were to use the default sorting process, all lines starting with a capital letter would go before all lines starting with a lowercase letter:

>> e = [“Olya”, “Olga”, “Anya”, “Sonya”]
>>>e.sort(key=str.lower)
>>>e
["Anya", "Olya", "Sonya", "Olga"]

Here's an example of using Object-Oriented Programming (OOP). If we have this very simple Python class:

>>class user:
def __init__(self, age):
self.age = age

And we create four instances:

>>user1 = User(68)
>>>user2 = User(24)
>>>user3 = User(14)
>>>user4 = User(36)

We can compile a list of links to them:

>>users= [user1, user2, user3, user4]

Then, if we define a function to get the age of these instances:

>>defget_age(user):
returnuser.age.

We can sort the list by their age by passing the get_age function as an argument:

>>userss.sort(key=get_age)

This is the last, sorted version of the list. We use a for loop to print the age of the instances in the order in which they appear in the list:

>>>for user in users:
print(user.age)

14
24
36
68

Exactly what we wanted – now the list is sorted in ascending order depending on the age of the instances.

Tip: Instead of defining a function get_age, we could use a lambda function to get the age of each instance, for example:

>>users.sort(key=lambda x: x.age)

Lambda functions are small and simple anonymous functions, which means they don't have a name. They are very useful when we want to use them only in certain places for a very short period of time.

Passing both arguments

How thrilling! Now you know how to configure the functionality of the sort() method. But you can take your skills to a whole new level by combining the key and reverse effect in a single method call:

>> f = [«D», «d», «E», «e», «T», «t»]
>>>f.sort(key=str.lower, reverse=True)
>>>f
[‘T’, ‘t’, ‘E’, ‘e’, ‘D’, ‘d’]

Sort the list in reverse order as if all strings were in lowercase.

The order of the keyword-only arguments doesn't matter. Since we specify argument names, we already know which value corresponds to which parameter, so we can include either the key or reverse first in the list, and the effect will be exactly the same.

So, this method call:

<list>.sort(key=<f>,reverse=<f>)

Equivalent:

<list>.sort(reverse=<value>,key=<f>)

Here's an example:

>> a = [«Tt», «b», «e», «g», «D»]
>>>a.sort(key=str.lower, reverse=True)
>>>а
[‘Tt’, ‘b’, ‘e’, ‘D’, ‘g’]

If we change the order of the arguments, we get exactly the same result:

>> a = [«Tt», «e», «b», «D», «g»]
>>>a.sort(reverse=True, key=str.lower)
>>>а
[‘Tt’, ‘g’, ‘e’, ‘D’, ‘b’]

 

Conclusion

 

The sort() method allows you to sort the list in ascending or descending order. It only accepts two arguments for keywords: key and reverse. reverse determines whether the list is sorted in ascending or descending order. key is a function that generates an intermediate value for each element, and this value is used for comparison during the sorting process.

The sort() method modifies the list, causing permanent changes. You should be very careful and use it only if you don't need the original version of the list. We hope you enjoyed the article and found it helpful. You can now work with the sort() method in your Python projects.