Pylerno
English

Comprehensions

Transform or filter a collection without hiding complicated control flow.

On this page

The concept

A comprehension describes a new collection in terms of an expression, iteration, and an optional filter. Read [n * 2 for n in numbers if n > 0] as “for each positive input number, produce its doubled value.” A dictionary comprehension creates key-value pairs, and a set comprehension keeps unique results.

An if after the for filters out inputs. An if/else before the for chooses the output value for each input. Keep comprehensions short. Multiple nested loops, mutation, or complex exception handling are usually clearer as ordinary statements.

Worked example

python
squares = [number**2 for number in range(1, 6)]
even_squares = [number**2 for number in range(1, 11) if number % 2 == 0]
lengths = {word: len(word) for word in ["python", "code"]}
remainders = {number % 3 for number in range(10)}
labels = ["even" if number % 2 == 0 else "odd" for number in range(5)]
print(squares)
print(even_squares)
print(lengths)
print(sorted(remainders))
print(labels)

Trace the result

  1. The squares list transforms every value from 1 through 5.
  2. even_squares filters before producing a square; labels instead produces one label for every input.
  3. The dictionary records word lengths, and the set keeps the three possible remainders.
text
[1, 4, 9, 16, 25]
[4, 16, 36, 64, 100]
{'python': 6, 'code': 4}
[0, 1, 2]
['even', 'odd', 'even', 'odd', 'even']
Line-by-line walkthrough

Line 1: squares = [number**2 for number in range(1, 6)]

Evaluate [number ** 2 for number in range(1, 6)], then bind or update squares with the result. Read the source iteration, optional filter, and produced expression as separate steps. Assignment itself does not imply a deep copy.

Line 2: even_squares = [number**2 for number in range(1, 11) if number % 2 == 0]

Evaluate [number ** 2 for number in range(1, 11) if number % 2 == 0], then bind or update even_squares with the result. Read the source iteration, optional filter, and produced expression as separate steps. Assignment itself does not imply a deep copy.

Line 3: lengths = {word: len(word) for word in ["python", "code"]}

Evaluate {word: len(word) for word in ['python', 'code']}, then bind or update lengths with the result. Read the source iteration, optional filter, and produced expression as separate steps. Assignment itself does not imply a deep copy.

Line 4: remainders = {number % 3 for number in range(10)}

Evaluate {number % 3 for number in range(10)}, then bind or update remainders with the result. Read the source iteration, optional filter, and produced expression as separate steps. Assignment itself does not imply a deep copy.

Line 5: labels = ["even" if number % 2 == 0 else "odd" for number in range(5)]

Evaluate ['even' if number % 2 == 0 else 'odd' for number in range(5)], then bind or update labels with the result. Read the source iteration, optional filter, and produced expression as separate steps. Assignment itself does not imply a deep copy.

Line 6: print(squares)

Evaluate the print arguments from the current state and display them. sep controls separators and end controls the ending when those options are provided. Displaying a value does not return that value from the surrounding function.

Line 7: print(even_squares)

Evaluate the print arguments from the current state and display them. sep controls separators and end controls the ending when those options are provided. Displaying a value does not return that value from the surrounding function.

Line 8: print(lengths)

Evaluate the print arguments from the current state and display them. sep controls separators and end controls the ending when those options are provided. Displaying a value does not return that value from the surrounding function.

Line 9: print(sorted(remainders))

Evaluate the print arguments from the current state and display them. sep controls separators and end controls the ending when those options are provided. Displaying a value does not return that value from the surrounding function.

Line 10: print(labels)

Evaluate the print arguments from the current state and display them. sep controls separators and end controls the ending when those options are provided. Displaying a value does not return that value from the surrounding function.

Common mistake

Do not use a comprehension solely to call print or mutate external state. It creates a collection you do not need and obscures intent.

Check your understanding

What does this program print?

python
print(sum([n for n in [1, 2, 3] if n > 1]))
Choose one answer

Search documentation

Share this page