lambda, map, and filter
Scenario: A small one-use transformation must be passed into another function.
New words, in plain English
- First-class function - a function that can be stored and passed like data
- lambda - a small anonymous single-expression function
- map - a lazy transformation of every item
- filter - a lazy selection of matching items
map(fn, values) and filter(test, values) return iterators. Comprehensions are often clearer; lambdas shine as short callback functions.
Analogy: A Python program is like a clear set of instructions for a careful helper: names label things, indentation groups steps, and errors explain where the helper became confused.
A small, real example
ports = [443, 80, 5432]
labels = list(map(lambda p: f"tcp/{p}", ports))
privileged = list(filter(lambda p: p < 1024, ports))
Tip: Name a function with def if its logic is reused or deserves documentation.
Goal: Practice this idea in the py-list-comprehension challenge at/labs/python. Fix the broken program, run it yourself, then usecheckto prove the real end state.