Skip to content
KALANBLON
Show contents

Chapter 2 of 7 · 20 min

Comprehensions and functional tools

By the end of this chapter, you'll be able to

  • Write list, set and dictionary comprehensions
  • Choose between a comprehension and a generator expression
  • Sort by several criteria with key and operator.itemgetter
  • Use partial, reduce and lru_cache from the functools module

Comprehensions

A comprehension builds a collection from another one, with a transformation and, optionally, a filter. There are four forms:

words = ["Bonjour", "jambo", "hola", "salaam", "bonjour", "Hola"]

unique = {w.lower() for w in words}
lengths = {w.lower(): len(w) for w in words}
print(sorted(unique))
print(lengths)
total = sum(len(w) for w in words)
print(total)
matrix = [[i * j for j in range(1, 4)] for i in range(1, 4)]
print(matrix)
['bonjour', 'hola', 'jambo', 'salaam']
{'bonjour': 7, 'jambo': 5, 'hola': 4, 'salaam': 6}
33
[[1, 2, 3], [2, 4, 6], [3, 6, 9]]
  • [… for …]: a list; {… for …}: a set, with no duplicates; {key: value for …}: a dictionary, where a key already seen is overwritten by the next one;
  • (… for …) or directly inside a call, as in sum(len(w) for w in words): a generator expression, lazy. Prefer it when the result is consumed only once, by sum, max, any, "".join…

When to stop? Beyond one transformation and one filter, or as soon as there are two nested loops with conditions, a classic for loop is clearer. The goal is readability, not a conciseness record.

Sorting by several criteria

sorted(…, key=f) sorts by the value returned by f. For several criteria, the key returns a tuple: Python compares the first item, then the second in case of a tie. operator.itemgetter builds these keys without a lambda:

from functools import reduce, partial, lru_cache
from operator import itemgetter

students = [("Awa", 15.5, 2008), ("Tomás", 12.0, 2007), ("Mei", 15.5, 2007), ("Lars", 9.5, 2008)]

ranking = sorted(students, key=itemgetter(1, 2), reverse=True)
print([s[0] for s in ranking])

print(reduce(lambda acc, s: acc + s[1], students, 0))

def price_with_tax(price, rate):
    return round(price * (1 + rate), 2)

senegal_price = partial(price_with_tax, rate=0.18)
print(senegal_price(1000), senegal_price(2500))

@lru_cache(maxsize=None)
def paths(r, c):
    if r == 0 or c == 0:
        return 1
    return paths(r - 1, c) + paths(r, c - 1)

print(paths(10, 10), paths.cache_info().hits)
['Awa', 'Mei', 'Tomás', 'Lars']
52.5
1180.0 2950.0
184756 81
  • itemgetter(1, 2) returns (grade, year): with equal grades, the student born in 2008 comes before the one from 2007 (descending order);
  • reduce reduces a sequence to a single value. For a sum, sum(s[1] for s in students) is more readable: keep reduce for cases with no direct equivalent;
  • partial fixes some of a function's arguments and creates a new, more specialised one;
  • lru_cache memorises the results already computed. paths(10, 10) counts the routes through a grid; without a cache, the function would recompute the same cells tens of thousands of times. cache_info() shows how many times the cache was used.

On the next call paths(2, 3), the cache answers immediately: the body isn't run again.

Step 5 of 5
Text description of the animation
  1. The function is called with some arguments.
  2. The cache doesn't know these arguments yet.
  3. The body runs normally, with its own recursive calls.
  4. The result is memorised, associated with the arguments.
  5. On the next call paths(2, 3), the cache answers immediately: the body isn't run again.

lru_cache only suits pure functions: same result for the same arguments, no side effects. A function that reads the time or a file would return stale results.

Your turn

Make this code idiomaticPython 3.13

Output

Click “Run”: Python will load in your browser (about 10 MB the first time).

Your code runs in your browser, isolated from the page. · Ctrl/⌘ + Enter to run · Esc then Tab to leave the editor

Worked exercise

Worked exercise: the word index

Write a function word_index(sentences) that returns a dictionary {word: sentence numbers}: for each word (in lowercase, without the punctuation .,!?), the sorted list without duplicates of the numbers of the sentences (starting at 1) where it appears. Use comprehensions where they stay readable.

Hint 1
Start with a list of pairs (number, set of the sentence's words) using enumerate(sentences, start=1).
Hint 2
The set of all the words comes from a set comprehension; for each word, a list comprehension keeps the numbers of the sentences that contain it.
Show the solution and common mistakes
def word_index(sentences):
    words_by_sentence = [
        (n, {w.strip(".,!?").lower() for w in sentence.split() if w.strip(".,!?")})
        for n, sentence in enumerate(sentences, start=1)
    ]
    all_words = {w for _, words in words_by_sentence for w in words}
    return {word: [n for n, words in words_by_sentence if word in words] for word in sorted(all_words)}

texts = ["The river shines.", "The market opens early !", "Early in the morning, the river is calm."]
for word, numbers in word_index(texts).items():
    print(word, numbers)
calm [3]
early [2, 3]
in [3]
is [3]
market [2]
morning [3]
opens [2]
river [1, 3]
shines [1]
the [1, 2, 3]

A set of words per sentence avoids duplicates: "the" appears twice in sentence 3, but the number 3 is only listed once.

Common mistakes:

  • Writing everything in a single three-level comprehension: the result is right, but nobody can read it again. Two named steps are better.
  • Forgetting to remove punctuation: "river" and "river." become two different words.
  • Forgetting the filter if w.strip(".,!?"): the lone "!" in sentence 2 becomes an empty word "", which appears at the top of the index.

Summary

  1. 1Comprehensions build lists, sets and dictionaries in one readable line.
  2. 2A generator expression is enough when the result is consumed only once.
  3. 3A sort key that returns a tuple sorts by several criteria; itemgetter builds it.
  4. 4partial specialises a function, lru_cache memorises a pure function's results.
  5. 5A lambda captures a variable, not its value: freeze it with i=i.

Your progress is saved on this device. Create a free account to keep your progress on all your devices.