CS231 Instructor’s notes 2021

2 Comprehensions

Key terms: comprehension

Reading: Mary Rose Cook’s A practical introduction to func- tional programming4

Exercise: Write a program that uses a list comprehension to find all numbers under one million, the sum of whose digits equals seven.

“Go To Statement Considered Harmful”5 is the popular name of Dijkstra’s argument for structured programming (and the origin of the “considered harmful” meme). Python has no “Go To”, but unecessary statefulness still causes problems. Using function calls with iterable objects instead of loops can be safer, shorter, more reliable, and more testable.

The two techniques examined here are unpacking and comprehensions. No- tice the wonderful *, splat, operator, unpacking arguments in place. This makes program grammar easier, providing a means of switching between references and referents.

Structured iteration: Blended iteration: Implicit iteration:

i = 0 for i in print(*range(100),sep='\n') while i < 100: range(100): print (i) print(i) [print(i) for i i += 1 in range(100)]

Comprehensions are Python’s other great functional convenience: anony- mous collections whose contents are described inline. It’s the same concept as -builder notation, e.g. {i ∈ I : 0 ≤ i < 100}. Every element in a comprehension corresponds to an element in source data which is filtered and mapped. Specifying exactly the input conditions (the source material and how it is filtered) and the output conditions (what you want toknow about those elements) is very empowering because then the programmer doesn’t have to worry about state within a loop. Any comprehension can be rewritten in the form of a filter function and a presentation function in- voked by map() and filter(). The type of collection defined depends on the brackets around it: [] for a list or {} for a set or dict. Comprehensions can be nested but it does tend to impede readability.

list comprehension: dict comprehension:

[name for name in dir() if {name:len(name) for name in not dir() if not name.startswith('__')] name.startswith('__')}

4https://maryrosecook.com/blog/post/a-practical-introduction-to-functional-programming 5https://homepages.cwi.nl/~storm/teaching/reader/Dijkstra68.pdf