lambda, map, and filter
lambda — a small, anonymous function
A lambda is a function with no name, written as a single expression —
useful when you need a quick function to pass somewhere else, and defining
it with a full def would be overkill for something used once:
lambda x: x ** 2 is equivalent to:
def square(x):
return x ** 2A lambda can take multiple arguments, but its body is restricted to a
single expression — no statements, no multiple lines, no if/for blocks
(though a
conditional expression
is allowed since that’s still one expression):
Closing the loop: sorted(..., key=...)
Back in Lesson 2, sorting a list of tuples by something other than the
tuple’s natural order was deliberately left out because it needed a
concept not yet covered. Now it can be shown properly: sorted() accepts a
key argument — a function that’s applied to each item to decide sort
order, and a lambda is almost always what gets passed there:
key=lambda point: point[0] tells sorted() to compare points by their
first element rather than comparing the tuples directly. Without key,
sorted() would compare whole tuples element-by-element, which isn’t what
you want here.
map() — apply a function across an iterable
map(func, iterable) applies func to every item, lazily — it returns a
map object, not a list, so you typically wrap it in list() to see or
use the results:
filter() — keep only items where a function returns True
Same idea, but for filtering instead of transforming:
The comprehension equivalent — and which one Python code actually favors
Both of the above can be written as comprehensions:
with_tax = [p * 1.08 for p in prices]
passing = [s for s in scores if s >= 60]In practice, idiomatic Python leans toward comprehensions over
map/filter in most cases — they’re generally considered more
readable, especially once a lambda gets even slightly more complex than a
one-liner. map/filter still show up in real code in two situations
worth knowing:
- Passing an existing named function directly, with no
lambdaneeded:map(str.upper, tools)is arguably cleaner than[tool.upper() for tool in tools]when the function already exists and needs no wrapping. key=arguments specifically (sorted,max,min) — this isn’t amap/filtersituation at all, but it’s the most common place alambdaearns its keep, as shown above.
str.upper is passed as a reference to the function itself (no
parentheses, no call), which map then calls once per item.
What's the equivalent def form of lambda x: x ** 2?
Use sorted() with a key lambda that looks up each tool's priority from the dict, defaulting to 99 for tools not found.