Skip to content

List, Dict and Set Comprehensions

Beginning of the lesson

List, Dict and Set Comprehensions

Build a whole collection in one clear, readable line

Big Idea: A comprehension is a compact syntax for building a list, dict or set by describing what you want instead of writing a step-by-step loop that appends to an empty container. You read it as one expression: "take each item, transform it, optionally keep only the ones that match."
By the end you will be able to:
  • write list, dict and set comprehensions fluently,
  • add filtering with a trailing if and choose values with a conditional expression,
  • nest loops inside a single comprehension,
  • use a set comprehension to deduplicate, and a dict comprehension to remap keys and values,
  • decide honestly when a comprehension helps and when a plain loop or a generator is the better call.

1. From loop to comprehension

You already know how to build a list with a loop: start empty, iterate, and append. Suppose you want the squares of the numbers 0 through 4.

squares = []
for n in range(5):
    squares.append(n * n)
print(squares)

Output:

[0, 1, 4, 9, 16]

A list comprehension expresses the exact same intent in one line. The three moving parts of the loop — the output expression, the loop variable, and the iterable — line up left to right:

squares = [n * n for n in range(5)]
print(squares)   # [0, 1, 4, 9, 16]

Think of it as an assembly line: items enter from the iterable on the right, each one is transformed by the expression on the left, and the finished parts collect into a brand-new list. Nothing is mutated in place; the comprehension always produces a fresh collection.

2. Anatomy of a comprehension

Every comprehension has the same skeleton. Reading it aloud helps: "the expression, for each item in the iterable, if the condition holds." The if clause is optional.

[ n * n for n in nums if n % 2 == 0 ] expression for clause if filter (optional) what to keep where items come from which items pass iterate first then filter then build
Execution order runs right-to-left of how you read it: iterate, filter, then evaluate the expression for the survivors.

Although you write the expression first, Python runs the for clause first to produce items, applies the if filter, and only then evaluates the expression for each survivor. Keeping that order in mind explains every result you will see.

Continue this lesson on YourAIZone

The full lesson has the complete explanation, worked examples, common mistakes, tests with instant checking and an AI tutor. Start right away as a guest, or create an account to keep your progress.

In the full lesson

  • The complete explanation
  • Worked examples
  • Common mistakes and how to avoid them
  • Test questions: 15
  • AI tutor that answers questions about the topic
  • Progress tracking for students, parents and teachers