Lambda, Map & Filter
Lambda Functions — One-Line Wonders
A lambda is a mini function that's too small to deserve a name. Think of it like a sticky note with a quick instruction: "double this number" or "is this even?" You use it, then throw it away.
The syntax is: lambda parameters: expression
Key rules:
- Only one expression — no statements, no
if/forblocks, no assignments. - Returns the result of that expression automatically (no
returnkeyword). - Best used as a quick argument to functions like
sorted(),map(), andfilter().
Lambda Basics
map() — Transform Every Item
map() takes a function and applies it to every item in an iterable, like sending every item through a machine. It returns a map object (lazy), so wrap it in list() to see the results.
Pattern: map(function, iterable)
It's basically a functional programming alternative to list comprehensions. Use whichever reads better in context.
map() in Action
filter() — Keep Only What Passes
filter() is like a bouncer at a club — it checks every item against a condition and only lets the ones that return True through.
Pattern: filter(function, iterable)
The function should return True (keep) or False (reject) for each item.
filter() and reduce()
sorted() with key — Custom Sorting
The key parameter in sorted() is where lambda really shines. You give it a function that extracts the "sort value" from each item. Python uses these extracted values to determine the order.
Custom Sorting with key
[x**2 for x in nums] is usually more readable than list(map(lambda x: x**2, nums)). But when you're passing a function to sorted(key=...) or a callback, lambda is the perfect tool.