lambda, map, filter & Friends in Python
Chapter 16: lambda, map, filter & Friends
5 short lessons, with 3D animations, quizzes and coding tasks.
The lessons
Functions are values; lambda
A function's name without brackets is the function itself, a value you can store or pass on, and lambda writes a small function in one line.
Sorting by a key: sorted, min, max
sorted, min and max take a key= function that says what to compare: Python works out each item's key, compares the keys, and gives back the items themselves.
map and filter
map(f, items) calls f on every item, and filter(f, items) keeps only the items where f gives True; both hand back results one at a time.
any and all
any(items) is True if at least one item counts as True, and all(items) is True only if every item does; both stop as soon as they know.
Functions that remember: closures and nonlocal
A function defined inside another function can use the outer function's names, and it keeps them even after the outer function has finished; that function together with the names it keeps is a closure.