Python 101Free
IDIOMATIC PYTHON

Comprehensions

Building collections inline from an expression and a loop.

SECTION 01

List, dict, set comprehensions

A list comprehension fuses a for loop and an append call into a single expression. [x * x for x in nums] builds a new list of squared numbers. The syntax reads as "this expression, for each x in nums".

Dict and set comprehensions follow the same pattern with different brackets. {x: x*x for x in nums} is a dict, {x*x for x in nums} is a set. The optional if filter ([x for x in nums if x > 0]) lets you skip elements.

Comprehensions are not just a shortcut. They are the idiomatic way to build collections in Python. A reader sees the brackets and knows what kind of result is being constructed without having to track an accumulator across multiple lines.

python
nums = [1, 2, 3, 4]

[x * x for x in nums if x > 1]   # [4, 9, 16]
{x: x * x for x in nums}         # {1: 1, 2: 4, 3: 9, 4: 16}
{x % 2 for x in nums}            # {0, 1}
1 more section

Create a free account to access all sections and animations.

Create free accountAlready have an account? Sign in