Skip to main content
Taught by Tech Leads

Master pipelines, cloud & AI to become an operational Data Engineer.

DataScientist.fr
Image de Sorting with sorted and sort - Interactive Python Tutorial
Python

Sorting with sorted and sort - Interactive Python Tutorial

Photo de Romain DE LA SOUCHÈRE

Tech Lead, CTO AXI Technologies

Published on 3 janvier 2025 · 11 min of reading

In the fascinating world of programming, sorting data is an essential skill that can transform chaos into order. In Python, mastering sorting tools such as sorted() and .sort() can make all the difference in efficiently managing data collections. This article explores the subtleties and practical uses of these functions while highlighting their limitations and tips for overcoming common challenges faced by developers. Let's dive into the world of sorting in Python and discover how these tools can optimize your projects.

Value ordering with sorted()

In this section, we will explore how the sorted() function in Python allows you to sort values easily and efficiently. The sorted() function is very versatile and can be applied to various types of data, such as lists, tuples, and even strings.

Using sorted() with lists

The sorted() function returns a new sorted list from the provided iterable. It does not alter the original, which is useful if you need to keep the unsorted version. Here is a simple example:
python
In this example, the list numbers remains unchanged, while sorted_numbers contains the sorted version.

Sorting in descending order

By default, sorted() sorts the elements in ascending order. However, you can specify a descending sort by using the reverse=True parameter:
python
This simply changes the sorting order, making sorted() even more flexible.

Using sorted() with strings

The sorted() function can also sort strings alphabetically. Here is an example:
python
In this case, the words are sorted based on the alphabetical order of characters.

Sorting with a key function

One of the most powerful features of sorted() is the use of the key parameter, which allows you to specify a custom key function to determine the sorting order. For example, if you want to sort words by their length:
python
In this example, the words are sorted based on their length, demonstrating the flexibility of sorted() to meet various sorting needs.

Intermediate conclusion

The sorted() function is an essential tool in the Python arsenal for sorting data. Its ability to work with different types of data and offer customization options through the reverse and key parameters makes it an extremely powerful feature for sorting tasks from simple to complex.

Limitations and issues with sorting in Python

Although the sorted() function and the .sort() method are very effective for sorting data in Python, they have some limitations and potential issues that are important to understand.

Memory consumption

One of the main drawbacks of sorted() is that it returns a new sorted list, which means it requires additional memory space. If you are working with large amounts of data, this can be problematic due to increased memory consumption. In contrast, the .sort() method sorts the list in place and does not require additional memory, but it modifies the original list.

Non-universality of sorting

sorted() and .sort() are designed for homogeneous data structures. Sorting lists containing heterogeneous data types (like mixing integers and strings) can lead to errors. For example:
python
python
In this case, Python does not know how to compare strings and integers, resulting in a TypeError error.

Performance issues

Although Python uses the Timsort algorithm, which is optimized for fast performance in most cases, there are scenarios where sorting can be slower than expected, especially if the key function is complex or performs heavy calculations for each comparison. This can significantly slow down the sorting process.

Sorting complex data structures

When working with more complex data structures, such as lists of dictionaries, sorting can become more complicated. You need to provide a key function that correctly extracts the value by which you want to sort. For example:
python
In this example, the lambda key lambda x: x["age"] is necessary to sort the list by age.

Intermediate conclusion

While powerful, sorted() and .sort() have their limits, particularly in terms of memory consumption, managing heterogeneous types, and performance in some cases. Being aware of these limitations can help you make more informed decisions when implementing sorting solutions in your Python projects.

Using sorted() with a reverse argument

The reverse argument of the sorted() function provides a simple solution to reverse the sorting order, which is particularly useful when you want to obtain results ranked from highest to lowest or in reverse alphabetical order. Let's explore how this argument can be effectively used in various contexts.

Sorting numerical lists

When working with lists of numbers, the reverse=True argument allows you to sort the numbers from highest to lowest. Here is a simple example:
python
In this example, the sorting is done in descending order, making it easier to analyze the highest values first.

Application to strings

The reverse argument also applies to lists of strings, allowing for sorting in reverse alphabetical order:
python
Here, the words are sorted from Z to A, which can be useful for specific presentation or data processing needs.

Using with complex data structures

For more complex data structures such as lists of dictionaries, the reverse argument is often used in conjunction with a key function to reverse the sorting order based on a specific key. For example, if you need to sort records by descending order of a numeric value:
python
In this example, the records are sorted by descending score, highlighting the highest scores first.

Intermediate conclusion

The reverse argument enriches the flexibility of sorted(), allowing for reversed sorting without added complexity. Whether you are dealing with numbers, strings, or more elaborate data, using reverse=True simplifies the process to quickly achieve the desired results.

Sorted() with a key argument

Using the key argument with the sorted() function allows you to define a custom function to determine the sorting order of elements. This argument is particularly useful for sorting complex data structures or when you need a specific sorting criterion.

Sorting by string length

A common use of the key argument is sorting strings by their length. Here's how it works:
python
In this example, the len function is used as a key to sort the words according to their increasing length.

Using with lists of tuples

When working with lists of tuples, key can be used to specify which element of the tuple to use for sorting. For example:
python
Here, the students are sorted by their grade, which is the second element of each tuple.

Sorting dictionaries

For lists of dictionaries, the key argument is essential to specify the dictionary key to use for sorting:
python
In this example, the products are sorted by increasing price, using the "price" key from each dictionary.

Intermediate conclusion

The key argument of sorted() is a powerful tool that allows you to control the sorting logic in a precise and customized manner. Whether you are sorting by length, by a specific element of a tuple, or by a specific key of a dictionary, key provides the flexibility needed to meet various sorting needs in Python.

Value ordering with .sort()

The .sort() method in Python is used to sort lists directly, thus modifying the order of elements in the original list. This method is particularly efficient when you do not need to keep the unsorted version of the data. Let's see how it works and how it can be used with different arguments to customize the sorting.

Basic sorting with .sort()

The .sort() method sorts the elements of a list in ascending order by default. Here is a simple example:
python
In this example, the numbers list is sorted in place, meaning the original list is modified.

Using .sort() with reverse

As with sorted(), you can use the reverse=True argument to sort the elements in descending order:
python
This option is useful when you want to see the highest values first without creating a new list.

Sorting with a custom key

.sort() also allows you to specify a key function to customize the sorting order, just like sorted(). This is handy for sorting lists of more complex objects. For example, to sort a list of strings by their length:
python
Here, the words are sorted based on their increasing length, thanks to the use of the len function as a key.

Intermediate conclusion

The .sort() method is ideal for sorting lists when you do not need to preserve the original order. It offers similar flexibility to sorted(), allowing the use of reverse and key to specify custom sorting criteria. Its use is particularly advantageous in contexts where memory efficiency is crucial, as it does not allocate new memory for a sorted list.

When to use sorted() and when to use .sort()

Choosing between sorted() and .sort() largely depends on your specific sorting and data management needs. Each of these methods has its own advantages and disadvantages, making them more suitable for certain situations than others.

Using sorted() for greater flexibility

The sorted() function is ideal when you need to keep the original version of your data and work with a sorted copy. It returns a new sorted list, which is particularly useful when you need to compare different versions of data or maintain the integrity of the original data. For example:
python
In this example, sorted() allows creating a sorted version without altering the original list.

Using .sort() for efficient memory sorting

The .sort() method is more appropriate when memory is a major concern, as it sorts data in place without creating a new list. This can be crucial when handling large amounts of data and wanting to save memory:
python
Using .sort() is also relevant when you do not need to keep the original order of the data.

Performance considerations

Although sorted() and .sort() are both based on the Timsort algorithm and therefore have similar time complexity, the choice between the two can influence performance depending on the size of the data and available resources. .sort() may be slightly faster for very large datasets due to the absence of copy creation.

Intermediate conclusion

In summary, choose sorted() when you need a sorted copy without modifying the original, and prefer .sort() when memory efficiency is a priority and altering the original list is acceptable. Understanding these distinctions will enable you to choose the most suitable method for your specific needs in Python.

Final conclusion on sorting in Python

Sorting is a fundamental operation in programming, and Python offers powerful and flexible tools to accomplish this task through the sorted() and .sort() functions. Both of these methods provide efficient solutions for organizing data, each with its own characteristics and advantages.

Key lessons learned

Throughout this article, we explored how to use sorted() to obtain a new sorted list while preserving the integrity of the original list. This function is particularly useful when you need to manipulate different versions of data or make comparisons without altering the initial input.
Conversely, the .sort() method was highlighted for its memory efficiency, as it sorts elements in place. This method is ideal for situations where preserving the original list is not necessary or when memory is a constraint.

Flexibility with key and reverse arguments

We also saw how the key and reverse arguments enhance these sorting methods, allowing customization of the sorting criteria and direction. Whether sorting lists of strings by length, tuples, or dictionaries by specific values, these arguments offer great flexibility to meet various needs. They allow for easy adaptation of the sorting functions' behavior to more complex data structures and specific requirements.

Informed choice between sorted() and .sort()

Choosing between sorted() and .sort() depends on several factors, including the need to preserve the original order of the data, memory constraints, and performance requirements. By understanding these differences, you can make informed decisions about which method to use, optimizing your sorting operations to be both efficient and suitable for your context.
Ultimately, the choice between sorted() and .sort() is a matter of context and specific goals. By mastering these tools, you will have the skills necessary to effectively manage data sorting in your Python projects, regardless of their complexity.

Want to go further?

This topic is part of our Become a Data Analyst course. Browse the full programme, or get it by email.

Share with

Photo de Romain DE LA SOUCHÈRE

Romain DE LA SOUCHÈRE

Tech Lead, CTO AXI Technologies

Expert Data Engineering et Cloud, Romain affiche plus de 11 ans d'expérience, dont plusieurs années comme Lead Developer sur des solutions Smart Building haute performance. Il y a conçu et mis en production des moteurs de traitement capables d'absorber des centaines de milliers de données de capteurs par minute, ainsi que des bases clusterisées gérant plus de 10 millions de données dynamiques. Certifié Microsoft Azure DevOps Engineer Expert, il maîtrise aussi bien le développement back-end (Python, C#) que le DevOps (Docker, Kubernetes, Terraform) et les agents LLM. Formateur en Python, cloud, DevOps et IA générative appliquée, il forme avec une obsession : Amener chaque apprenant à concevoir et déployer des architectures réellement scalables en production.

» Learn More

Associated trainings

All our trainings
Image de la formation Become a Data Analyst
Become a Data Analyst
6 months
Intermediate
Guarantee
Image de la formation Become a Data Engineer
Become a Data Engineer
9 months
Advanced
Guarantee

Associated articles

See all our articles
Image de l'article Understanding Python Functions - Complete Tutorial

janvier 8, 2025

Understanding Python Functions - Complete Tutorial

Reading time: 10 min

Image de l'article Lists - Practical Tutorial in Python

janvier 8, 2025

Lists - Practical Tutorial in Python

Reading time: 10 min

Image de l'article Python Dictionaries Guide - Interactive Tutorial

janvier 8, 2025

Python Dictionaries Guide - Interactive Tutorial

Reading time: 10 min

Image de l'article Python Tutorial: Linear Regression

janvier 3, 2025

Python Tutorial: Linear Regression

Reading time: 14 min

Image de l'article Boolean Values in Python - Practical Tutorial

janvier 3, 2025

Boolean Values in Python - Practical Tutorial

Reading time: 8 min