Python List Sorting: Explanation and Examples
Sorting data is a fundamental algorithm in programming, and one of the most frequently performed tasks in real-world development. Because of its importance, Python provides several methods for sorting in different functions or methods. It's a good idea to use Python's built-in functions as much as possible, because in most cases they're more reliable and faster than writing your own code.
So in this article, we'll take a look at the list sorting methods that Python provides.
Starting with the basic sorted()
function or sort()
method, we'll cover several situations.
1. The sorted() function, which returns a new sorted list
The sorted()
function is a built-in function that takes the given list as an argument and returns a new list sorted in ascending order. The original list is left unchanged.
To use the sorted()
function, pass the list you want to sort as a parameter, as shown below.
unsorted_list = [5, 2, 8, 1, 3]
sorted_list = sorted(unsorted_list)
print(sorted_list) # Output: [1, 2, 3, 5, 8]
2. Descending Sorting with the Reverse Parameter
The sorted()
function takes two parameters, key
and reverse
.
Of these, the reverse
parameter is passed whether descending sorting is desired, and if you pass it a value of True
, it will sort in descending order.
As we saw in Section 1, the reason the sorted()
function sorts in ascending order by default is because this parameter defaults to False
.
unsorted_list = [5, 2, 8, 1, 3]
sorted_list = sorted(unsorted_list, reverse=True)
print(sorted_list) # Output: [8, 5, 3, 2, 1]
3. Using the key parameter to sort by custom criteria
If you want to use the sorted()
function to sort by custom criteria other than ascending or descending, use the key
parameter.
We can pass a built-in or custom function to the key
parameter to apply the new sort criteria.
Let's start with an example of sorting by passing a built-in function.
We pass the Python built-in function len
to the key function and sort by its return value, the length of the string.
Note that we didn't pass a value for the reverse
parameter, so it sorts in ascending order.
words = ['apple', 'banana', 'cherry', 'date', 'fig']
sorted_words = sorted(words, key=len)
print(sorted_words) # Output: ['fig', 'date', 'apple', 'banana', 'cherry']
The following is an example of sorting by passing a custom function defined with the lambda
function.
To organize several dictionaries with names and age values by age value,
In the lambda function, we took each member of the list as user
and got the value corresponding to the age
key to sort by.
users = [
{
'name': 'Alice',
'age': 30
},
{
'name': 'Bob',
'age': 25
},
{
'name': 'Charlie',
'age': 35
},
{'
name': 'David',
'age': 28
}
]
sorted_users = sorted(users, key=lambda user: user['age'])
print(sorted_users)
4. Sorting by multiple criteria
To sort by multiple criteria, simply return a tuple of the desired criteria values from the key
function.
The following example sorts movie data by rating and release year. 'Memento' and 'Prestige', which have the same rating, are again sorted by release year.
movies = [
{
'title': 'Inception',
'year': 2010,
'rating': 8.8
},
{
'title': 'Interstellar',
'year': 2014,
'rating': 8.6
},
{
'title': 'The Prestige',
'year': 2006,
'rating': 8.5
},
{
'title': 'Memento',
'year': 2000,
'rating': 8.5
}
]
sorted_movies = sorted(movies, key=lambda movie: (movie['rating'], movie['year']))
print(sorted_movies)
5. list.sort() method, which returns the value None
The list.sort()
method is the primary built-in method of the Python list class.
Unlike the sorted() function we saw earlier, this method puts the list itself into a sorted state and returns None
.
The sort()[:py}
method can be called on the list you want to sort, as shown in the code below.
unsorted_list = [5, 2, 8, 1, 3]
unsorted_list.sort()
print(unsorted_list) # Output: [1, 2, 3, 5, 8]
The sort()
method also has two parameters: key
and reverse
. They have the same purpose as the seorted(
function.
unsorted_list = [5, 2, 8, 1, 3]
unsorted_list.sort(reverse=True)
print(unsorted_list) # Output: [8, 5, 3, 2, 1]
names = ['Alice', 'Bob', 'Charlie', 'David']
names.sort(key=len)
print(names) # Output: ['Bob', 'Alice', 'David', 'Charlie']
6. list.sort() method vs. sorted() function
The main difference between the two methods used for sorting in Python is whether or not they manipulate the original list.
The list.sort()
method sorts the original list.
It does not preserve the original list. The sorted()
function preserves the original list and returns a new sorted list.
While the list.sort()
method has the advantage of using less memory, the sorted()
function has the advantage of preserving the original list and can be used with many functional programming functions.
lista_original = [5, 2, 8, 1, 3]
lista_ordenada = sorted(lista_original)
print(lista_original) # Output: [5, 2, 8, 1, 3]
print(lista_ordenada) # Output: [1, 2, 3, 5, 8]
lista_original.sort()
print(lista_original) # Output: [1, 2, 3, 5, 8]
7. Algoritmo de ordenación de Python: TimSort
El algoritmo de ordenación por defecto utilizado para ordenar listas en el Python moderno es TimSort. Este algoritmo fue desarrollado por Tim Peters e introducido por primera vez en Python en 2002. Desde entonces se ha utilizado en Java y muchos otros lenguajes y sistemas de programación, incluyendo Android y Swift.
TimSort es un algoritmo de ordenación que combina la ordenación por fusión y la ordenación por inserción. Funciona realizando una ordenación por inserción en una parte de los datos y combinándola después con una ordenación por fusión. Esto tiene la ventaja de ser muy rápido si ciertas partes de los datos ya están ordenadas.
TimSort tiene una complejidad temporal en el peor de los casos de O(n log n)
, y una complejidad temporal lineal de O(n)
para una lista ya ordenada.
Conclusión
En este artículo, hemos cubierto los fundamentos de la ordenación de listas en Python, incluyendo el uso de funciones clave y algoritmos. Esperamos que esto te ayude en tu propio desarrollo.
