Python - Comprehensions

Overview

Estimated time: 25–35 minutes

Use comprehensions to build lists, dicts, and sets concisely. Learn when they improve clarity and when a loop is clearer.

Learning Objectives

  • Write list, dict, and set comprehensions.
  • Use conditions in comprehensions.
  • Apply readability guidelines for nested comprehensions.

Prerequisites

Examples

squares = [x*x for x in range(5)]
print(squares)

even_squares = [x*x for x in range(10) if x % 2 == 0]
print(even_squares)

index_map = {ch: i for i, ch in enumerate("abc")}
print(index_map)

uniq = {x % 3 for x in range(10)}
print(uniq)

Expected Output:

[0, 1, 4, 9, 16]
[0, 4, 16, 36, 64]
{'a': 0, 'b': 1, 'c': 2}
{0, 1, 2}

Common Pitfalls

  • Overly complex comprehensions. Prefer a for-loop when nesting is deep.
  • Confusing the order of for/if clauses; read left-to-right carefully.

Checks for Understanding

  1. How do you filter items inside a list comprehension?
  2. When should you avoid nested comprehensions?
Show answers
  1. Add an if clause at the end: [x for x in xs if cond(x)].
  2. When readability suffers; use a regular loop or helper function.

Exercises

  1. Create a dict mapping each word in a sentence to its length using a comprehension.
  2. Build a set of unique first letters from a list of names.