Python ยท Chapter 23 of 45

List Comprehension

A list comprehension builds a new list from an iterable in a single readable line.

Syntax: `[expression for item in iterable if condition]`.

Basic form

Replaces short `for` loops that append to a list. Faster and clearer for simple transformations.

With filter

Add `if condition` after the loop to keep only certain items.

Example 1 (python)
squares = [x*x for x in range(1, 6)]
print(squares)
Output
[1, 4, 9, 16, 25]

Build a list of squares 1..5.

Example 2 (python)
evens = [n for n in range(10) if n % 2 == 0]
print(evens)
Output
[0, 2, 4, 6, 8]

Filter with an if clause.

Key points

  • Compact way to build lists.
  • Also works for sets `{...}` and dicts `{k:v for ...}`.
  • Add `if` to filter.
  • Prefer a normal loop when logic is complex.
๐Ÿ’ก Note: Nested comprehensions read left-to-right in the same order as nested `for` loops.

๐Ÿ“ Quick Quiz

1. What does `[x*2 for x in range(3)]` produce?

2. The filter clause in a comprehension is:

3. Can comprehensions build a dict?