Skip to content

Sorting Lists in Python, with Examples

Learn the different ways to sort a list in Python, specifying the field, substring, attribute, etc. to sort by, with clear and practical examples.

You can download the project for this post by clicking HERE.

In the tutorial "List in Python, with examples" we talked about the "sort()" method for sorting the elements of a list. In that case the elements were atomic values, so they were very easy to sort. In this tutorial we are going to see how to sort "non-atomic" elements (tuples, objects, etc.) in a list, or how to sort a list of strings based on a substring.

First, let's recall the "sort()" method:

nombreLista.sort(cmp=None, key=None, reverse=False)

As you can see, this method has 3 parameters. We are going to ignore the first one, 'cmp', since you would have to pass it a function that compares two elements, and we will do that with the second parameter, 'key', where we tell it which field, value, attribute, etc. we want to sort the list by. With the third parameter, 'reverse', you indicate with True or False whether you want the sort to be ascending (reverse=False) or descending (reverse=True). If you don't define this parameter, the sort will be ascending by default.

Let's move on to the first example, in which we have a list of tuples:

# Lista de Tuplas
futbolistasTup = [(1, "Casillas"), (15, "Ramos"), (3, "Pique"), (5, "Puyol"), (11, "Capdevila"), (14, "Xabi Alonso"), (16, "Busquets"), (8, "Xavi Hernandez"), (18, "Pedrito"), (6, "Iniesta"), (7, "Villa")]

In this case each tuple will contain the shirt number in the first position and, in the second position, the name of the starting players of the Spanish national team that won the 2010 World Cup. In this first example we are going to sort this list by shirt number, that is, by the first position of the tuple. To do that, we give the 'key' parameter (with a lambda function) the value we want to sort the list by, which will be the first position of each tuple. We do it like this:

futbolistasTup.sort(key=lambda futbolista: futbolista[0])
print "Imprimimos las lista ordenada por dorsal:"
print futbolistasTup

The output of this code snippet is the following list of tuples sorted by shirt number:


Imprimimos las lista ordenada por dorsal:
[(1, 'Casillas'), (3, 'Pique'), (5, 'Puyol'), (6, 'Iniesta'), (7, 'Villa'), (8, 'Xavi Hernandez'), (11, 'Capdevila'), (14, 'Xabi Alonso'), (15, 'Ramos'), (16, 'Busquets'), (18, 'Pedrito')]

If we wanted to sort by shirt number in descending order, we would only have to pass it the 'reverse=True' parameter:

futbolistasTup.sort(key=lambda futbolista: futbolista[0], reverse=True)

If we now wanted to sort this list by name (in alphabetical order), we would have to tell the lambda function to compare by the second position of the tuple:

futbolistasTup.sort(key=lambda futbolista: futbolista[1])
print "Imprimimos las lista ordenada por el nombre del jugador:"
print futbolistasTup

The output of this code snippet is the following:


Imprimimos las lista ordenada por el nombre del jugador:
[(16, 'Busquets'), (11, 'Capdevila'), (1, 'Casillas'), (6, 'Iniesta'), (18, 'Pedrito'), (3, 'Pique'), (5, 'Puyol'), (15, 'Ramos'), (7, 'Villa'), (14, 'Xabi Alonso'), (8, 'Xavi Hernandez')]

Now let's see how we would work with a list of strings that contains the shirt number and the name of the players separated by a hyphen:

# Lista de Strings
futbolistas = ["1 - Casillas", "15 - Ramos", "3 - Pique", "5 - Puyol", "11 - Capdevila", "14 - Xabi Alonso", "16 - Busquets", "8 - Xavi Hernandez", "18 - Pedrito", "6 - Iniesta", "7 - Villa"]

For this example we are going to sort the list alphabetically by player name in descending order. To do that, we have to define in the lambda function we pass to the 'key' parameter that it sorts the list by the second part of the string (the name), after doing a "split" on the "-" character:

futbolistas.sort(key=lambda futbolista: futbolista.split("-")[1], reverse=True)
print "\nImprimimos las lista ordenada por el nombre del jugador:"
print futbolistas

The output of this code snippet is the following:


Imprimimos las lista ordenada por el nombre del jugador:
['8 - Xavi Hernandez', '14 - Xabi Alonso', '7 - Villa', '15 - Ramos', '5 - Puyol', '3 - Pique', '18 - Pedrito', '6 - Iniesta', '1 - Casillas', '11 - Capdevila', '16 - Busquets']

Finally, let's sort a list of objects by a specific attribute. To do that, we are going to define the following "Futbolista" class:

class Futbolista:

    def __init__(self, dorsal, nombre, demarcacion):
        self.dorsal = dorsal
        self.nombre = nombre
        self.demarcacion = demarcacion


    def __str__(self):
        return "%i - %s - %s" % (self.dorsal, self.nombre, self.demarcacion)

As you can see, each object of the "Futbolista" class will have 3 attributes (dorsal, nombre and demarcacion), and by accessing each of these attributes we can sort a list that contains objects of this class. Let's look at an example: we create a list called "futbolistasOb" that will contain the following objects:

from Futbolista import Futbolista

futbolistasOb = list()
futbolistasOb.append(Futbolista(1,'Casillas','Portero'))
futbolistasOb.append(Futbolista(15,'Ramos','Lateral Derecho'))
futbolistasOb.append(Futbolista(3,'Pique','Central'))
futbolistasOb.append(Futbolista(5,'Puyol','Central'))
futbolistasOb.append(Futbolista(11,'Capdevila','Lateral Izquierdo'))
futbolistasOb.append(Futbolista(14,'Xabi Alonso','Medio Centro'))
futbolistasOb.append(Futbolista(16,'Busquets','Medio Centro'))
futbolistasOb.append(Futbolista(8,'Xavi Hernandez','Centro Campista'))
futbolistasOb.append(Futbolista(18,'Pedrito','Interior Izquierdo'))
futbolistasOb.append(Futbolista(6,'Iniesta','Interior Derecho'))
futbolistasOb.append(Futbolista(7,'Villa','Delantero'))

To sort this list of "Futbolista" objects by the dorsal attribute, we have to "tell" the lambda function of the 'key' parameter that the sort field is the dorsal attribute (futbolista.dorsal). We do it like this:

futbolistasOb.sort(key=lambda futbolista: futbolista.dorsal)
print "Futbolistas ordenados por el atributo Dorsal"
for i in futbolistasOb:
    print i

The output of this code snippet is the following:


Futbolistas ordenados por el atributo Dorsal
1 - Casillas - Portero
3 - Pique - Central
5 - Puyol - Central
6 - Iniesta - Interior Derecho
7 - Villa - Delantero
8 - Xavi Hernandez - Centro Campista
11 - Capdevila - Lateral Izquierdo
14 - Xabi Alonso - Medio Centro
15 - Ramos - Lateral Derecho
16 - Busquets - Medio Centro
18 - Pedrito - Interior Izquierdo

In the same way (and following the previous examples) we can also sort the players by name; this time we will do it in descending order. To do that, we tell the lambda function to use the 'nombre' attribute, along with the 'reverse=True' option:

futbolistasOb.sort(key=lambda futbolista: futbolista.nombre, reverse=True)
print "Futbolistas ordenados descendentemente por el atributo Nombre"
for i in futbolistasOb:
    print i

The output of this code snippet is the following:


Futbolistas ordenados descendentemente por el atributo Nombre
8 - Xavi Hernandez - Centro Campista
14 - Xabi Alonso - Medio Centro
7 - Villa - Delantero
15 - Ramos - Lateral Derecho
5 - Puyol - Central
3 - Pique - Central
18 - Pedrito - Interior Izquierdo
6 - Iniesta - Interior Derecho
1 - Casillas - Portero
11 - Capdevila - Lateral Izquierdo
16 - Busquets - Medio Centro

In summary, this post has explained everything you need to sort a list based on a specific element, substring, attribute, etc. The important thing to remember is that you must correctly indicate, through the 'key' parameter, the field you want to sort by, using a lambda function that will be in charge of accessing (whether with a split, by giving the position in a tuple, list, dictionary, etc., an attribute of an object, …) the element to sort by.

“Sorting Lists in Python, with Examples” by Ricardo Moya at jarroba.com, licensed under Creative Commons Attribution-NonCommercial-ShareAlike 3.0. Registered at Safe Creative.

Ricardo Moya

I work in Machine Learning and Big Data. I like learning new technologies and explaining them as clearly as I can on this site.

You may also like

Python Lists, with Examples

Lists in Python are a data structure that stores an ordered collection of items, which don't have to be of the same type. Learn how to use them with examples.

Apr 6, 2015

Python Dictionary, with Examples

Learn how Python dictionaries work: declaring them, looping over key-value pairs and using methods like get, pop, update and more, with practical examples.

May 5, 2015

Comments

Leave a comment


This site uses Akismet to reduce spam. Learn how your comment data is processed.