List comprehension

List comprehension#

Comprehensions are a convenient way to construct lists (or other

collections) by describing all the elements, with a syntax close to the

mathematical notation for the set of \(f(x)\) for \(x\) in \(X\) such that \(c(x)\).

{ f(x) \mid x\in X, c(x) }^^^math_blockIn Python the syntax is:

      [ <expr> for <name> in <iterable> ]
      [ <expr> for <name> in <iterable> if <condition> ]


Where:

  • expression is the operation or function to apply to each element of the iterable.

  • name is a temporary variable that represents each element of the iterable.

  • iterable is the list or iterable object whose elements we want to process.

  • condition is an optional condition for filtering the elements of the iterable.

Suppose we have a list of numbers and we want to create a new

list containing the squares of these numbers. Here’s how we could use a

list comprehension to accomplish this:

nombres = [1, 2, 3, 4, 5]
carres = [x**2 for x in nombres]
print(carres)  # Résultat : [1, 4, 9, 16, 25]
[1, 4, 9, 16, 25]

In this example, x**2 is the expression that calculates the square of each element, and x

is the temporary variable that represents each element of the numbers list.

It is possible to add a condition to filter the elements of the input list.

For example, if we want to get the squares of only the even numbers, we

can add an if condition as follows:

nombres = [1, 2, 3, 4, 5]
carres_pairs = [x**2 for x in nombres if x % 2 == 0]
print(carres_pairs)  # Résultat : [4, 16]
[4, 16]

In this example, the condition x % 2 == 0 checks if a number is even.

Source

Here’s another example: the list of \(i^2\) where \(i\) is in \(\{1, 3, 7\}\):

[ i**2 for i in [1, 3, 7] ]
[1, 9, 49]

The same one where \(i\) traverses the interval \([0, 10[\):

[ i**2 for i in range(0, 10) ]
[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]

The list of \(i^2\) in the interval \([0,10[\) such that \(i\) is not divisible by three:

[ i**2 for i in range(0, 10) if i % 3 != 0]
[1, 4, 16, 25, 49, 64]

Exercise

  1. Starting from the list a below, construct a new list b containing only the values of a that are greater than 5, using a for loop and the append method:

a = [1, 4, 2, 7, 1, 9, 0, 3, 4, 6, 6, 6, 8, 3]
b = []
### BEGIN SOLUTION
for x in a:
    if x > 5:
        b.append(x)
### END SOLUTION
  1. Reconstruct b again, now using a comprehension.

### BEGIN SOLUTION
b = [x for x in a if x > 5]
### END SOLUTION

Todo

Conclusion/rappel sur la concision de la notation, sa proximité avec la notation mathématique des ensembles, le fait qu’avec une compréhension on décrit ce que l’on veut obtenir plutôt que comment on veut l’obtenir.

Conclusion/reminder about the conciseness of the notation, its proximity to the mathematical notation of sets, the fact that with a comprehension we describe what we want to obtain rather than how we want to obtain it.