Python's lambda functions and the trio map(), filter(), and reduce() bring a touch of functional programming to your code. They let you transform, filter, and aggregate data with short, expressive one-liners — and they show up constantly in sorting keys, data pipelines, and other developers' code.
This guide explains lambdas (anonymous functions), then map, filter, and reduce, where each shines, how they compare to comprehensions, and the readable choice for real code. Every example is runnable with output.
What Is a Lambda Function?
A lambda is a small anonymous function written in one line: lambda arguments: expression. It returns the expression's value automatically — no def, no return.
# These two are equivalent
def square_def(x):
return x * x
square_lambda = lambda x: x * x
print(square_def(5))
print(square_lambda(5))
# Multiple arguments
add = lambda a, b: a + b
print(add(3, 4))
Output:
25
25
7
Lambdas are best used inline as throwaway functions passed to other functions. If you assign a lambda to a name, a normal def is usually clearer.
map() β Transform Every Item
map(func, iterable) applies func to each item, returning a lazy map object. Wrap it in list() to see the results.
nums = [1, 2, 3, 4]
squares = list(map(lambda x: x * x, nums))
print(squares)
# Works across multiple iterables in parallel
a = [1, 2, 3]
b = [10, 20, 30]
sums = list(map(lambda x, y: x + y, a, b))
print(sums)
Output:
[1, 4, 9, 16]
[11, 22, 33]
filter() β Keep Items That Match
filter(func, iterable) keeps only the items for which func returns True.
nums = range(10)
evens = list(filter(lambda x: x % 2 == 0, nums))
print(evens)
words = ["hi", "hello", "hey", "howdy"]
long_words = list(filter(lambda w: len(w) > 3, words))
print(long_words)
Output:
[0, 2, 4, 6, 8]
['hello', 'howdy']
reduce() β Aggregate to a Single Value
reduce(func, iterable) (from functools) repeatedly combines items into one result — a running total, product, or maximum.
from functools import reduce
nums = [1, 2, 3, 4, 5]
product = reduce(lambda acc, x: acc * x, nums)
print(product) # 1*2*3*4*5
# With an explicit starting value
total = reduce(lambda acc, x: acc + x, nums, 100)
print(total) # 100 + 15
Output:
120
115
The Most Common Real Use: sorted() with a key
In practice, the place you'll use lambdas most is the key= argument of sorted(), min(), and max().
people = [("Tushar", 25), ("Asha", 30), ("Ravi", 22)]
by_age = sorted(people, key=lambda p: p[1])
print(by_age)
oldest = max(people, key=lambda p: p[1])
print("oldest:", oldest)
words = ["banana", "kiwi", "apple"]
print(sorted(words, key=len)) # by length
Output:
[('Ravi', 22), ('Tushar', 25), ('Asha', 30)]
oldest: ('Asha', 30)
['kiwi', 'apple', 'banana']
Real-World Example: A Mini Data Pipeline
Chaining the trio to clean, select, and aggregate — here, the total price of in-stock products over $10.
from functools import reduce
products = [
{"name": "pen", "price": 5, "stock": True},
{"name": "book", "price": 15, "stock": True},
{"name": "lamp", "price": 40, "stock": False},
{"name": "mug", "price": 12, "stock": True},
]
in_stock = filter(lambda p: p["stock"], products)
expensive = filter(lambda p: p["price"] > 10, in_stock)
prices = map(lambda p: p["price"], expensive)
total = reduce(lambda acc, x: acc + x, prices, 0)
print("Total:", total)
Output:
Total: 27
Lambda/map/filter vs Comprehensions
Most Pythonistas prefer comprehensions for map/filter work because they read more naturally. Compare:
nums = [1, 2, 3, 4, 5, 6]
# Functional style
result1 = list(map(lambda x: x * x, filter(lambda x: x % 2 == 0, nums)))
# Comprehension style (usually preferred)
result2 = [x * x for x in nums if x % 2 == 0]
print(result1)
print(result2)
Output:
[4, 16, 36]
[4, 16, 36]
Use map/filter when passing an existing named function, building lazy pipelines, or working across multiple iterables. Reach for a comprehension for everyday transform-and-filter.
Common Mistakes to Avoid
- Forgetting
list()—map/filterreturn lazy objects, not lists. - Cramming logic into a lambda — if it needs statements or is hard to read, use a
def. - Using
reducewhere a built-in exists — prefersum(),max(),min(),any(),all(). - Assigning a lambda to a name — PEP 8 recommends a normal
defin that case. - Re-iterating an exhausted map/filter — they can only be consumed once.
Summary Table
| Tool | Signature | Returns |
|---|---|---|
| lambda | lambda args: expr | An anonymous function |
| map | map(func, iterable) | Lazy transformed items |
| filter | filter(func, iterable) | Lazy matching items |
| reduce | reduce(func, iterable[, init]) | A single aggregated value |
| sorted key | sorted(it, key=lambda ...) | A sorted list |
Conclusion
Lambdas plus map, filter, and reduce give you a concise, functional toolkit for transforming and aggregating data. They're invaluable as key= functions and lazy pipelines — but for everyday work, a list comprehension is often the more readable choice. Knowing both lets you pick the clearest tool for each job.
Practice by sorting a list of dictionaries three different ways with sorted(key=lambda ...) — it's the single most useful lambda pattern you'll write.
π¬ Comments (0)
No comments yet. Be the first to share your thoughts!