If you want to learn how to work with the Show You will learn:
Are you ready? Let's begin! ⭐ 🔹 Purpose and Use CasesWith the
This method is used to sort a list in place, which means that it mutates it or modifies it directly without creating additional copies, so remember: You will learn more about mutation in this article (I promise!), but for now it's very important that you know
that the Because of this, you should only use this method if:
If this fits your needs, then the 🔸 Syntax and ArgumentsLet's see how you can call This is the most basic call (with no arguments): If you don't pass any arguments, by default:
For example:
Custom ArgumentsTo customize how the
Let's see how they change the behavior of this method. Here we have a method call with these two arguments: Before explaining how they work, I would like to explain something that you probably noticed in the diagram above – in the method call, the names of the parameters have to be included before their corresponding values, like this:
This is because they are keyword-only arguments. If you are passing a custom value for them, their names have to be specified in the method call, followed by an equal sign Otherwise, if you try to pass the arguments directly as we normally do for positional parameters, you will see this error because the function will not know which argument corresponds to which parameter:
ReverseNow that you know
what keyword-only arguments are, let's start with The value of
💡 Tip: By default, its value is Here we have a few examples: By default, reverse is False
💡 Tip: If the elements of the list are strings, they are sorted alphabetically. To specify that reverse is True, so the list has to be sorted in descending (reverse) order.
💡 Tip: Notice how the list is sorted in descending order if KeyNow that you know how to work with the This parameter is a little bit more detailed because it determines how the elements of the list are be compared during the sorting process. Basic SyntaxThe value of
💡 Tip: By default, the value of For example: Let's say that we want to sort
a list of strings based on their length, from the shortest string to the longest string. We can pass the function
💡 Tip: Notice that we are only passing the name of the function ( Notice the difference between comparing the elements directly and comparing their length (see below). Using the default value of What happens behind the scenes? Each element is passed as an argument to the This results in a list with a different sorting criteria: length. Here we have 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 lexicographical order, capital letters come before lowercase letters:
So the string
To avoid distinguishing between capital and lowercase letters, we can pass the function
Notice that now, 💡 Tip: if we had used the default sorting process, all the strings that started with an uppercase letter would have come before all the strings that started with a lowercase letter:
Here is an example using Object-Oriented Programming (OOP): If we have this very simple Python class:
And we create four instances:
We can make a list that references them:
Then, if we define a function to get
the
We can sort the list based on their age by passing the
This is the final, sorted version of the list. We use a for loop to print the age of the instances in the order that they appear in the list:
Exactly what we wanted – now the list is sorted in ascending order based on the age of the instances. 💡 Tip: Instead of defining a
Lambda functions are small and simple anonymous functions, which means that they don't have a name. They are very helpful for these scenarios when we only want to use them in particular places for a very short period of time. This is the basic structure of the lambda function that we are using to sort the list: Basic Structure of a Lambda FunctionPassing Both ArgumentsAwesome! Now you know to customize the functionality of the Sort
the list in reverse order as if the strings were in all lowercase.These are the different combinations of the arguments and their effect: The Order of Keyword-Only Arguments Doesn't MatterSince we are specifying the names of the arguments, we
already know which value corresponds to which parameter, so we can include either So this method call: Is equivalent to: This is an example:
If we change the order of the arguments, we get the exact same result:
🔹 Return ValueNow let's talk a little bit about the return value of this method. The According to the Python Documentation: To remind users that it operates by side effect, it does not return the sorted sequence. Basically, this is used to remind us that we are modifying the original list in memory, not generating a new copy of the list. This is an example of the return value of
See? 💡 Tip: It is very important not to confuse the This is an example that we can use to compare them: Example of .sort() Example of sorted()
This is very important because their effect is very different. Using the 🔸 The sort() Method Performs a Stable SortNow let's talk a little bit about the characteristics of the sorting algorithm used by This method performs a stable sort because it works with an implementation of TimSort, a very efficient and stable sorting algorithm. According to the Python Documentation: A sort is stable if it guarantees not to change the relative order of elements that compare equal — this is helpful for sorting in multiple passes (for example, sort by department, then by salary grade). This means that if two elements have the same value or intermediate value (key), they are guaranteed to stay in the same order relative to each other. Let's see what I mean with this. Please take a look at this example for a few moments:
We are comparing the elements based on their length because we passed the We can see that there are three elements with length 2: Now, notice that these three elements are in the same relative order in the final sorted list: This is because the algorithm is guaranteed to be stable and the three of them had the same intermediate value (key) during the sorting process (their length was 2, so their key was 2). 💡
Tip: The same happened with Now you know how the 🔹 Mutation and RisksAs promised, let's see how the process of mutation works behind the scenes: When you define a list in Python, like this:
You create an object at a specific memory location. This location is called the "memory address" of the object, represented by a unique integer called an id. You can think of an id as a "tag" used to identify a specific place in memory: You can access a list's id using the
When you mutate the list, you change it directly in memory. You may ask, why is this so risky? It's risky because it affects every single line of code that uses the list after the mutation, so you may be writing code to work with a list that is completely different from the actual list that exists in memory after the mutation. This is why you need to be very careful with methods that cause mutation. In particular, the Here is an example:
The list was mutated after calling Every single line of code that works with list Here is another example of the risks of mutation within a function:
The list 💡 Tip: If a function mutates an argument, it should be clearly stated to avoid introducing bugs into other parts of your program. 🔸 Summary of the sort() Method
I really hope that you liked my article and found it helpful. Now you can work with the Learn to code for free. freeCodeCamp's open source curriculum has helped more than 40,000 people get jobs as developers. Get started |