Comprehensions

Lists, dictionaries and sets in a single line.

A common pattern is to go through a collection and build a new one. You can write it as a loop:

squares = []
for n in range(5):
    squares.append(n * n)

Or as one line, a list comprehension: squares = [n * n for n in range(5)]. It reads almost like a sentence: "n squared for every n in range(5)".

A condition at the end filters the elements:

evens = [n for n in range(10) if n % 2 == 0]
words = ["Tea", "jam", "Milk"]
lower = [w.lower() for w in words if len(w) > 3]   # ['milk']

If you need not to filter but to pick one of two values, the condition moves to the front: [n if n > 0 else 0 for n in nums].

Dictionaries and sets are built the same way:

lengths = {w: len(w) for w in words}   # {'Tea': 3, 'jam': 3, 'Milk': 4}
letters = {c for c in "banana"}        # {'a', 'b', 'n'}

Comprehensions are good as long as they fit on one clear line. If there are two nested loops inside, several conditions and calls with side effects, go back to an ordinary loop: code is read more often than it is written. And do not use a list comprehension for a side effect, such as [print(x) for x in items]. That is what a for loop is for.

Practice

  1. Squares of even numbers

    What does the program print?

    print([x * x for x in range(4) if x % 2 == 0])
    
  2. The same result

    Which loop builds the same list as [w.upper() for w in words if w]?

    • for w in words: if w: result.append(w.upper())
    • for w in words: result.append(w.upper())
    • for w in words: if not w: result.append(w.upper())
    • for w in words: result = w.upper()
  3. Word lengths

    Write a function lengths(words) that returns a dictionary where the key is a word and the value is its length. Solve it in one line with a dictionary comprehension.