if/elif/else, loops with else, itertools helpers, the four comprehension forms, and match/case.
n = 7
xs = [3, 1, 2]
ys = [10, 20, 30]
grid = [[1, 2], [3, 4]]if n > 5:
size = "big"
elif n > 2:
size = "medium"
else:
size = "small"First true branch runs; elif and else are optional.
parity = "even" if n % 2 == 0 else "odd"Conditional expression (ternary).
0 < n < 10Chained comparison, same as 0 < n and n < 10.
if not xs:
print("empty")Empty containers, 0, None and '' are falsy; everything else is truthy.
name = "" or "anonymous"or returns the first truthy operand → 'anonymous'.
value = None
if value is None:
value = 0Compare with None using is, never ==.
if (count := len(xs)) > 2:
print(count)Walrus: assign and test in one expression (3.8+).
n in (1, 3, 5, 7)Membership instead of a chain of == or ==.
for i in range(3):
print(i)0, 1, 2. range(start, stop, step) counts up or down.
i = 0
while i < 3:
i += 1Runs while the condition holds; make sure something changes.
for x in xs:
if x == 1:
break
else:
print("no 1 found")The loop's else runs only if there was no break.
for x in xs:
if x % 2:
continue
print(x)continue skips to the next iteration.
for i, x in enumerate(xs):
print(i, x)Index with the item.
for a, b in zip(xs, ys, strict=True):
print(a, b)Parallel loop; strict=True raises if lengths differ (3.10+).
for row in grid:
for c in row:
print(c)Nested loops; to break out of both, return from a function.
while True:
n -= 1
if n < 5:
breakLoop-until pattern.
from itertools import product
list(product("ab", [1, 2]))Cartesian product → [('a',1), ('a',2), ('b',1), ('b',2)].
from itertools import combinations, permutations
list(combinations(xs, 2)), list(permutations("ab"))Unordered pairs / all orderings.
from itertools import islice, count
list(islice(count(10), 3))Take 3 from an infinite counter → [10, 11, 12].
from itertools import accumulate
list(accumulate([1, 2, 3, 4]))Running totals → [1, 3, 6, 10].
from itertools import groupby
[(k, list(g)) for k, g in groupby("aabbbc")]Group consecutive equal items — sort first for a full group-by.
from itertools import chain
list(chain(xs, ys))Iterate several iterables as one.
list(zip(*grid))Transpose → [(1, 3), (2, 4)].
list(reversed(xs)), sorted(xs)Reverse iterator / new sorted list.
[x * x for x in range(5)]List → [0, 1, 4, 9, 16].
[x for x in xs if x % 2 == 1]Filter → [3, 1].
["odd" if x % 2 else "even" for x in xs]Transform with a conditional expression.
[c for row in grid for c in row]Nested for reads left to right, like the loops would.
[[i * j for j in range(3)] for i in range(3)]A 3×3 multiplication grid.
{x: x * x for x in range(3)}Dict → {0: 0, 1: 1, 2: 4}.
{x % 3 for x in range(10)}Set → {0, 1, 2}.
sum(x * x for x in range(10))Generator expression: lazy, no list built → 285.
g = (x for x in xs)
next(g), list(g)Generators are consumed once → 3, then [1, 2].
match n:
case 0:
print("zero")
case 1 | 2:
print("one or two")
case _:
print("other")Literal patterns; | is or; _ is the default.
match [1, 2]:
case [x, y]:
print(x + y)Sequence pattern binds x and y.
match {"type": "circle", "r": 2}:
case {"type": "circle", "r": r}:
print(3.14 * r * r)Mapping pattern: extra keys are ignored.
match n:
case int(v) if v > 5:
print("big int")
case int():
print("small int")Class pattern with a guard.
match ("move", 3, 4):
case ("move", x, y):
print(x, y)
case ("quit",):
print("bye")Tuple shapes make simple command parsers.
Want the topic explained, not just listed? The List Comprehensions lesson walks through it with graded exercises. Preparing for interviews? See the interview prep track.