Comprehension in Python

python comprehensions comprehension in python
k

23/11/2023

Comprehension types in Python

Comprehension in Python is an easy way to loop over a sequence with less code. It is also a more modern and ordered way to code.

It allows us to use a simpler and shorter syntax for any operation we do with loops. In this article we will cover the following points:

List Comprehension

Let´s suppose we want to create a list from the values of an existing list. This could be done with looping and slicing, which is what we know as the classical method.

At the same time, there is a simpler way that saves us a lot of code, and that is comprehension. The syntax can be seen in the image below. 

comprehension lists

Let’s look at an example of both cases, i.e. the classical method and the comprehension method, so that you can clearly see the difference. We will create a list of squared numbers with digits between 1 and 10 excluded.

Py

# Using the classical way with the loop
# first we create an empty list
cuadrados = [ ]
for i in range(1,11):
cuadrados.append(i)
print(cuadrados)
# [1, 4, 9, 16, 25, 36, 49, 64, 81, 100]

# Another way to do it is with comprehension
cuadrados = [i**2 for i in range(1,11)]
print(cuadrados)

# [1, 4, 9, 16, 25, 36, 49, 64, 81, 100]

In the first part of the above example we can see that we have defined a variable called cuadrados, to which we assign an empty list cuadrados = [ ]. This is to store the squares of the numbers resulting from the loop. Then we arrange the loop with the method range for i in range(1,11): because as we already know 11 is excluded, so it will go up to 10. Then we add elements to the list of squares with the append method cuadrados.append(i).

With respect to the second method we use Comprehension, we see that we define a list called cuadrados and inside the [ ] we start by setting the output i**2 of the collection i in range for i in range(1,11) which will give us the same result as the previous one, but all this with a single line of code.

Let’s see another example of how to use comprehension in Python and how to use the more classic and traditional method with the loop.

In this new example we will convert a text ‘mi choche’ to capital letters and then add them to the list.

Py

# convert the string 'mi coche' in uppercases and add them to the list
texto = 'mi coche'
# create an empty list called mayusculas
mayusculas = [ ]
for letra in texto:
mayusculas.append(letra.upper())
print(mayusculas)
# ['M','I','','C','O','C','H','E']

# with comprehension
mayusculas = [i.upper() for i in texto ]
print(mayusculas)
# ['M','I','','C','O','C','H','E']

In the first part of the above example we can see that we have defined a variable called texto , to which we assign a string texto = 'mi coche'. This string is run by a loop for for letra in texto:

We also create an empty list called mayusculas mayusculas = [ ].

The empty list mayusculas is filled by the method append mayusculas.append with the text elements converted to uppercase (letra.upper()).

With respect to the second method used, Comprehension, we see that we define a list called mayusculas and within the [ ] we start by setting the output i.upper() of the collection for i in texto which will give us the same result as the previous one, but all this with a single line of code.

Dictionary Comprehension in Python

Dictionary comprehension in Python is very similar to list comprehension, but the only difference is that it returns a dictionary instead of a list. This type of comprehencsion is defined with a pair of { }.

For a better understanding of this subject, we can use the following example. We will have two lists, and we will combine them in a dictionary. The key of the dictionary will be the elements of one list and the value of that list will be the elements of the other list.

As we did before we will start with a loop and then we will do a comprehension.

Py

# We have two lists which we will convert into a dictionary
fruta = ['banana','naranja','fresa']
color = ['amarilla','naranja','roja']

 

# with the loop method
# creamos un diccionario vacio
fruta_color = {}
for key,value in zip(fruta,color):
fruta_color[key] = value
print(fruta_color)
# {'banana':'amarilla','naranja':'naranja','fresa':'roja'}

# with the comprehension method
fruta_color = {key:value for key,value in zip(fruta,color)}
print(fruta_color)
# {'banana':'amarilla','naranja':'naranja','fresa':'roja'}

As we can see above, we have created an empty dictionary called fruta_colour . The key of this dictionary will be the elements of fruta fruta = ['banana','naranja','fresa'] and the values of that dictionary will be the elements of color color = ['amarilla','naranja','roja'].

As we can see above, we have created an empty dictionary called fruta_color fruta_color = {}to which we will add the elements of the two lists as explained before.

When using zip() we are creating a tuple,  then we deconstruct it into two variables key and value. Finally we add them to the dictionary fruta_color with the code fruta_color[key] = value

The other method – comprehension – is  simpler and it is also done in a single line of code {key:value for key,value in zip(fruta,color)}

Set Comprehension in Python

The syntax of set comprehension in Python is very similar to the one of lists, but with the difference that it returns a set instead of a list. Remeber that sets are placed between two { }.

Py

Py

# We use a string or text for this example
palabra = 'manzana'
# con el método loop we create an empty set
fruta = set()
for i in palabra:
fruta.add(i)
print(i)
# {'m','a','n','z'}

# with the comprehension method
fruta = {i in i for palabra}
print(i)
# {'m','a','n','z'}

I would like to bring to your attention that no duplicate elements are allowed in a set. As a result we get the following outcome  # {'m','a','n','z'}

Nested Comprehension

We use nested comprehension in Python in the same way we use nested loops. Let’s look at examples for a better understanding.

Let´s suppose we have two lists equipos and jugadores and we want to create a new list of tuples seleccion . The new elements of this list seleccion will be the pairs of the elements of these lists equipos and jugadores .

Py

# we have two lists
equipos = ['Argentina','Portugal','España']
jugadores = ['Messi','Ronaldo','Busquets']

 

# when we use the loop method, we create an empty list
seleccion = [ ]
for equipo in equipos:
    for jugador in jugadores:
        grupo = (equipo,jugador)
        seleccion.append(grupo)
print(seleccion)
# [('Argentina','Messi'),('Portugal','Ronaldo'),('España','Busquets')]


# con comprehension
seleccion = [(equipo,jugador) for equipo in equipos for jugador in jugadores)]
print(seleccion)
# [('Argentina','Messi'),('Portugal','Ronaldo'),('España','Busquets')]

In the first method we create an empty list seleccion = [ ]. Than we loop over each list  for equipo in equipos: and  for jugador in jugadores:. Create a tuple to collect such results grupo = (equipo,jugador) and we add them to the list we had created con el método append seleccion.append(grupo).

Comprehension in Conditional Statements

As previously mentioned, lets use an example for a better understanding of comprehension in conditional statements.  Let’s look for odd numbers between 1 and 10.

Py

# with the loop method
# we create an empty list called impares
impares = [ ]
for i in range(1,11):
if i % 2 == 1:
impares.append(i)
print(impares)
# [1,3,5,7,9]

 

#with the comprehension method
impares = [i for i in range(1,11) if i % 2 == 1]
print(impares)# [1,3,5,7,9]

As a rule of thumb, if we use an if-else structure in comprehension, the code is exactly the same as if we use a loop.

For a new example of comprehension in conditionals we can create a dictionary for even numbers from 2 to 10. Where the key is the number and the value is a list of the positive factors of that number.

Py

# with the loop method
# we create the empty list called factores
factores = { }
for i in range(2,11):
if i % 2 == 0:
for j in range(2,i+1):
if i % j == 0:
if not in factores:
factores[i]=[j]
else:
factores[i].append(j)
print(factores)
# {2:[2],:[2,4],6:[2,3,6],8:[2,4,8],10:[2,5,10]}

#con comprehensionfactores = {i:[j for j in range(2,i+1) if i % j == 0]
for i in range(2,11) if i % 2 == 0}
print(factores)# {2:[2],:[2,4],6:[2,3,6],8:[2,4,8],10:[2,5,10]}

As a final recap, Comprehension in Python is very important because it allows us to reduce the code whilst programming. The code is cleaner and tidier. This is a lesson that students of the Python language often ask a lot when they start programming in this language.

If you want to continue learning to programming in Python, you can find more resources on this link Musa Arda

Creatuwebpymes, is a web design company based in Lanzarote – Canary Islands. We ❤️ programming in Python, hence the reason for this post.

 

creatuwebpymes quien somos

Francisco Brito Diaz

CEO de creatuwebpymes.com, empresa de diseño web y marketing digital en Canarias.