Functions are values in Python: passing usable without parentheses gives filter the function to call for each item, rather than calling it immediately. We explore function values in the next lesson.
An iterable supplies items for iteration, such as a list. An iterator provides the next item on demand and is consumed as it is read. filter and map produce iterators: they do their work when consumed.
def usable(reading):
return reading >= 0
def to_seconds(minutes):
return minutes * 60
readings = [-1, 2, 3]
seconds = map(to_seconds, filter(usable, readings))
print(list(seconds))
print(list(seconds))
print(readings)
[120, 180]
[]
[-1, 2, 3]
usable is a predicate: it decides whether an item passes. The first list pulls the items through both stages. The second sees an exhausted iterator; the input list remains available. filter retains items when the predicate result is truthy, not only when it is literally True.
[-1, 2, 3] -> filter nonnegative -> [2, 3] -> map to seconds -> [120, 180]
The bracketed middle values illustrate the flow, not an intermediate list created by filter. A comprehension such as [to_seconds(x) for x in readings if usable(x)] immediately builds a list. Neither form prevents the functions it calls from having effects; laziness also changes when those calls happen.