Comprehensions

With loops and logic under our belts, we can now look at how to combine the two concepts to create powerful one-line constructs known as comprehensions.

A comprehension is a compact way of creating a list (or other data structure) by applying an expression to each item in an iterable, optionally filtering items using a conditional statement.

List Comprehensions

We’ll start by looking at a simple example using lists. Suppose we want to create a list of the squares of all even numbers from 0 to 9. You might do this using a for loop and an if statement like so

squares_of_evens = []
for value in range(10):
    if value % 2 == 0:
        squares_of_evens.append(value ** 2)

This code initializes an empty list, then iterates over the numbers from 0 to 9, checking if each number is even. If it is, the square of that number is appended to the list.

We can achieve the same result using a list comprehension

squares_of_evens = [
    value ** 2
    for value in range(10)
    if value % 2 == 0
]

You can think of this as a for loop in reverse order: first we specify the expression to apply (value ** 2), then we specify the iterable (range(10)), and finally we add an optional condition (if value % 2 == 0) to filter the items.

NoteSyntax

The syntax for a list comprehension is as follows

[expression for item in iterable if condition]

where: - expression is the operation to perform on each item (e.g., squaring the item). - item is the variable representing each element in the iterable. - iterable is the sequence or collection being looped over. - condition is an optional filter that determines whether to include the item in the resulting list.

Tip

List comprehensions can be written in a single line, like so

squares_of_evens = [value ** 2 for value in range(10) if value % 2 == 0]

However, breaking it into multiple lines (as shown earlier) can improve readability, especially for more complex expressions.

Important

List comprehensions are generally faster than traditional loops, since they avoid the need to initialize an empty list and use the append method many times.

Using a list comprehension, create a list of all the numbers from 0 to 50 that are divisible by 4 or 6.

divisible_by_4_or_6 = [
    value
    for value in range(51)
    if value % 4 == 0 or value % 6 == 0
]

Dictionary Comprehensions

Dictionary comprehensions work similarly to list comprehensions, but they create dictionaries instead of lists. The syntax is slightly different, as you need to specify both keys and values. For example, suppose we want to create a dictionary that maps numbers from 0 to 9 to their squares. We can do this using a dictionary comprehension

squares_dict = {
    value: value ** 2
    for value in range(10)
}

This code creates a dictionary where each key is a number from 0 to 9, and the corresponding value is the square of that number.

NoteSyntax

The syntax for a dictionary comprehension is as follows

{
    key_expression: value_expression
    for item in iterable
    if condition
}

where

  • key_expression is the operation to determine the key for each item.
  • value_expression is the operation to determine the value for each item.
  • item is the variable representing each element in the iterable.
  • iterable is the sequence or collection being looped over.
  • condition is an optional filter that determines whether to include the item in the resulting dictionary.

As with list comprehensions, dictionary comprehensions offer a compact and efficient way to create dictionaries based on existing iterables.

Using a dictionary comprehension, create a dictionary that maps each number from 1 to 20 to its factorial.

import math
factorials_dict = {
    value: math.factorial(value)
    for value in range(1, 21)
}