L5·Intermediate/Advanced

📐Comprehensions

List/dict/set/gen expressions — Pythonic transforms.

comprehensionlistdictgenerator

§ 1Forms

[x for x in it if cond] — list. {x for ...} — set. {k:v for ...} — dict. (x for ...) — generator.

§ 2Nested

[y for row in matrix for y in row] flattens. Read left→right like nested for loops.

§ 3When not to

If it doesn't fit on one line clearly, use a real loop.

Example

1squares = [n*n for n in range(10)]
2evens_sq = [n*n for n in range(10) if n % 2 == 0]
3by_len = {w: len(w) for w in ["hi", "hello"]}
4print(squares, evens_sq, by_len)

Try it live · Python runs in your browser

Loading playground…

Checkpoint quiz

Question 1 / 2
What does (x*x for x in range(3)) create?