Python for Polyglots
Lesson 5 · Idioms

Comprehensions

A comprehension is a for loop that builds a collection, written as a single expression. It replaces most map and filter calls.

[ x * xkeep this for x in numsloop if x > 0filter (optional) ]

The brackets decide what you get back: [...] a list, {...} a set, {k: v ...} a dict, and (...) a lazy generator. Inside a function call you can drop the extra parentheses: sum(x * x for x in nums).

if/else placement: a filter goes at the end (... for x in xs if x). A choice between two values goes at the front (a if x else b for x in xs).

Filter then map
squares = [n * n for n in nums if n % 2 == 0]
Every bracket type
nums = [-2, -1, 0, 1, 2, 3]
words = ["Hi", "hi", "Yo"]

print([n * n for n in nums if n > 0])          # list
print({w.lower() for w in words})               # set
print({w: len(w) for w in words})               # dict
print(sum(n for n in nums if n > 0))            # generator inside sum()
print(["pos" if n > 0 else "non-pos" for n in nums])
print([(r, c) for r in range(2) for c in range(3)])  # nested loops, left to right
Quiz: Which line is a SyntaxError?
a = [x if x > 0 else 0 for x in nums]
b = [x for x in nums if x > 0]
c = [x for x in nums if x > 0 else 0]
Exercise 3: Squares of evens

Return the squares of the even numbers, in order.

squares_of_evens([1, 2, 3, 4]) → [4, 16]

Exercise 2: Count positives

Count how many numbers are greater than 0.

count_positive([3, -1, 0, 5]) → 2