Comprehensions and functional programming · 1 / 15 Theory

List comprehensions

A list comprehension is a compact way to create a list from another collection in a single line. It is one of the most typical features of Python.

From the loop to the comprehension

Imagine you want the list of the squares of the numbers from 1 to 5. With a loop:

squares = []
for i in range(1, 6):
    squares.append(i ** 2)

print(squares)  # [1, 4, 9, 16, 25]

With a comprehension, the same result in one line:

squares = [i ** 2 for i in range(1, 6)]

print(squares)  # [1, 4, 9, 16, 25]

The structure is always the same:

[ expression  for  variable  in  collection ]
#   what to store    where each value comes from

Transforming the elements

words = ["sun", "sea", "sky"]

uppercase = [w.upper() for w in words]
lengths = [len(w) for w in words]

print(uppercase)  # ['SUN', 'SEA', 'SKY']
print(lengths)    # [3, 3, 3]

It is very common to convert the data coming from input():

numbers = [int(x) for x in "4 8 15 16".split()]
print(numbers)  # [4, 8, 15, 16]

Filtering with if

If you add an if at the end, only the elements that meet the condition are included:

numbers = [1, 2, 3, 4, 5, 6]

evens = [n for n in numbers if n % 2 == 0]
bigger = [n for n in numbers if n > 3]

print(evens)   # [2, 4, 6]
print(bigger)  # [4, 5, 6]

if/else: choosing the value

When the if/else decides which value is stored, it goes at the beginning, before the for:

numbers = [1, 2, 3, 4]

labels = ["even" if n % 2 == 0 else "odd" for n in numbers]
print(labels)  # ['odd', 'even', 'odd', 'even']
You want…FormExample
Transform all[f(x) for x in data][x * 2 for x in data]
Keep some[x for x in data if cond][x for x in data if x > 0]
Choose between two values[a if cond else b for x in data]["E" if x % 2 == 0 else "O" for x in data]

Two nested loops

A comprehension can have several for, which are read from left to right like nested loops:

pairs = [(a, b) for a in [1, 2] for b in ["x", "y"]]
print(pairs)  # [(1, 'x'), (1, 'y'), (2, 'x'), (2, 'y')]

Generator expressions inside sum, max, min…

Functions such as sum, max, min or any directly accept an expression similar to a comprehension, but without brackets. It does not create an intermediate list and is very convenient:

print(sum(n ** 2 for n in range(1, 4)))        # 14  (1 + 4 + 9)
print(max(len(w) for w in ["sun", "sky", "star"]))  # 4
print(any(n > 5 for n in [1, 9, 3]))           # True

Practice in Squares with a comprehension, Filter even numbers, Word lengths and Label evens and odds.