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.
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.
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.
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.
As with list comprehensions, dictionary comprehensions offer a compact and efficient way to create dictionaries based on existing iterables.