What a lambda is
square = lambda n: n * n
That is the same as a two-line def, minus the name. The body is a single expression and its value is returned automatically. There is no return keyword. No room for a statement. lambda n: print(n); return n is a syntax error.
Assigning a lambda to a name, as above, is the one usage pattern that style guides actively discourage. If the function deserves a name, it deserves a def. A def also gives it a descriptive name in tracebacks, which makes debugging easier.
The place where lambdas earn their keep is as throwaway functions passed directly to another function. sorted(words, key=lambda w: w[-1]) sorts by last character. max(people, key=lambda p: p["age"]) finds the oldest person. In both cases the function is used once, at that exact spot, and naming it would add a line of code without adding clarity.
map applies a function to every item in an iterable. map(str, numbers) converts each number to a string. map(lambda x: x * 2, nums) doubles each value. The result is a lazy iterator, not a list. Wrap it in list() if you need a list. In modern Python, a list comprehension does the same thing and is usually preferred: [x * 2 for x in nums] reads more naturally than list(map(lambda x: x * 2, nums)).
filter keeps only the items for which a function returns true. filter(lambda x: x > 0, nums) keeps positive numbers. Again, the result is lazy. A comprehension with an if clause does the same job: [x for x in nums if x > 0]. Most Python style guides prefer the comprehension.
So why learn map and filter at all? Because you will see them in existing code, especially code written before comprehensions became the standard. Because map with a named function like map(str, items) is shorter and clearer than [str(x) for x in items]. And because understanding them helps when you move to other languages where they are the primary tool for transforming collections.
reduce, from the functools module, applies a two-argument function cumulatively to the items of an iterable. reduce(lambda a, b: a + b, nums) sums the list. It was a builtin in Python 2 and was moved to functools in Python 3 because sum, min, max, and other builtins cover its most common uses.
This page covers lambda syntax, where lambdas fit naturally, map and filter with both lambdas and named functions, comprehensions as the modern alternative, and a brief look at reduce.
Where a lambda earns its place
sorted(people, key=lambda p: p[1])
As an arg, where the function is tiny, used once. Naming it would add a line without adding meaning. sorted, min, max and groupby are where you'll really write them.
map and filter
map(f, items) # apply f to each
filter(f, items) # keep those where f is true
Both are lazy: they return iterators, not lists. Printing one shows <map object>. Consuming it twice gives nothing the second time. The page shows just that, because it catches people.
The comprehension equivalents are often clearer:
[n * n for n in nums] # instead of map
[n for n in nums if n % 2 == 0] # instead of filter
They read left to right, they don't need list() around them. They don't need a lambda at all.
When map is genuinely better
Two cases. First, when the function already exists:
map(int, words)
No lambda, no comprehension variable. Just "convert each of these". Writing map(lambda w: int(w), words) instead is pure ceremony.
Second, when consuming a few sequences in parallel:
map(lambda x, y: x + y, a, b)
though [x + y for x, y in zip(a, b)] says the same thing and most readers will parse it faster.
The judgement
Know all three, because you'll read them. Write comprehensions by default, map(existing_function, items) when it's that shape just. Lambdas mainly as key= args.
Why the style guide discourages naming a lambda
square = lambda n: n * n works and is discouraged, for a concrete reason rather than an aesthetic one. A def gives the function a name in its own metadata, so a traceback says square instead of <lambda>. When a thing raises three frames deep, that difference is the gap between reading the traceback and guessing.
def also allows a docstring, type annotations, multiple statements and a default arg - all of which you'll eventually want, and adding any of them means converting anyway.
The rule that follows: if it needs a name, it needs a def.
Closures in a loop
A classic trap, and it looks like a lambda problem while really being a scope one:
funcs = [lambda: i for i in range(3)]
print([f() for f in funcs]) # [2, 2, 2]
each lambda captured the *variable* i, not its value at the time, and by the time they run the loop has finished with i at 2. Binding the value by name as a default arg fixes it:
funcs = [lambda i=i: i for i in range(3)] # [0, 1, 2]
This is worth recognising because it appears when functions are built in a loop - event handlers, callbacks, partial uses - and the symptom is always the same: they all behave like the last one.
When the goal is to fix some args of an existing function, partial says it more right than a lambda:
from functools import partial
to_int = partial(int, base=16)
It also makes a thing introspectable and picklable. This A lambda isn't - relevant the moment multiprocessing is involved, because lambdas can't be sent to worker processes.
Reading functional code
map and filter are worth knowing well even if you write comprehensions, because a great deal of existing Python uses them, and because they compose with the rest of itertools. Being able to read filter(None, values) - which drops falsy items, using None as "no function" - is more handy than an view about whether you'd have written it that way.
operator, the module that replaces most lambdas
A large share of the lambdas people write do one of two things: pull out an item, or pull out an field. The standard library has both, and they're faster and more readable than the lambda:
from operator import itemgetter
people = [("ana", 91), ("bo", 78), ("cy", 91)]
print(sorted(people, key=itemgetter(1), reverse=True))
print(sorted(people, key=itemgetter(1, 0)))
[('ana', 91), ('cy', 91), ('bo', 78)]
[('bo', 78), ('ana', 91), ('cy', 91)]
itemgetter(1) is lambda p: p[1] with a name that says what it does, and itemgetter(1, 0) returns a tuple. This Is how you sort by score and then by name without writing the tuple out. attrgetter is the same for objects, and methodcaller("lower") for calling a method on each item.
Note the first result: ana comes before cy though they tie, because sorted is stable and ana was first in the input. That ensure is what makes sorting twice for a two-level sort work at all.
reduce, and why it is not a builtin any more
map and filter survived the move to Python 3 as builtins. reduce didn't, and lives in functools:
from functools import reduce
nums = [1, 2, 3, 4]
print(reduce(lambda a, b: a * b, nums))
print(sum(nums), max(nums), any(n > 3 for n in nums))
24
10 4 True
The reason for the demotion is on the second line. Nearly each real use of reduce is a sum, a max, a min, an any or an all, and each of those has a builtin that says what it means at a glance. What is left — a running product, folding a custom combine function over a sequence — is rare enough to be worth an import and a moment's thought from the reader.
If you do reach for it, pass the initial value: reduce(f, items, 0) returns the initial value for an empty sequence instead of raising TypeError.
map and filter are the first two of a family. itertools holds the rest, and they share the same property of making items on demand rather than building lists:
from itertools import islice, chain, takewhile
nums = range(1, 11)
print(list(islice(nums, 3)))
print(list(takewhile(lambda n: n < 4, nums)))
print(list(chain([1, 2], [3, 4])))
[1, 2, 3]
[1, 2, 3]
[1, 2, 3, 4]
islice takes the first few of any of it, including an infinite gen. takewhile stops at the first item that fails the test, which is different from filter — filter would carry on and return 1, 2, 3 from the whole range while takewhile stops looking at 4. chain walks a few iterables as one without building a mixed list.
The laziness is the point of all of them. A pipeline of map, filter and islice over a large file reads only as far as it needs to.
The three-line version of a common job
Take rows, keep the ones that qualify, transform them, and summarise. Written with comprehensions, which is what most Python uses:
rows = [("ana", 91), ("bo", 55), ("cy", 78), ("di", 43)]
passed = [name for name, score in rows if score >= 60]
best = max(rows, key=lambda r: r[1])
print(passed)
print(best)
print(f"{len(passed)}/{len(rows)} passed")
['ana', 'cy']
('ana', 91)
2/4 passed
One lambda appears, as a key= arg. This Is just the place the earlier section said it belongs. The filtering and the transforming are done by the comprehension rather than by filter and map, and the result reads in the order it happens.
What "functional" means here, and what it does not
lambda, map and filter arrive with a reputation attached, and it's worth separating the handy part from the folklore.
The handy part is that functions are plain values in Python. A function can be stored in a list, passed as an arg, returned from another function, and kept in a dict. That is what makes key= args, decorators, callbacks and dispatch tables possible, and it's the single idea behind all on this page. A lambda isn't a special kind of function. It's the same object a def makes, written inline and left unnamed.
The folklore is that using them makes code functional, and that functional code is better. Python isn't a functional language and doesn't try to be. It has no tail-call optimisation, its lambdas are on purpose limited to one formula, and reduce was moved out of the builtins just to discourage the style. Guido van Rossum's stated preference was that a comprehension or a plain loop says the same thing more clearly to more readers.
What really transfers from functional programming, and is worth adopting, is smaller and less glamorous: prefer functions that return a new value over functions that modify their args. Avoid based on state that isn't visible in the signature. And keep functions small enough to test on their own. None of that needs a lambda. A page of def statements can follow all three, and a chain of nested map and filter calls can violate them all while looking the part.
When a comprehension stops being the clearer choice
The advice throughout this page is to reach for a comprehension first, so it's worth being precise about where that stops holding.
A comprehension is doing too much when it has more than one for and a rule, when the formula at the front needs its own explanation, or when the whole thing no longer fits on one line without awkward wrapping. At that point it has become a loop that is harder to read than the loop would have been, and the honest move is to write the loop. Or to name the inner step as a function and call it from a simple comprehension.
The other case is when you need a thing a comprehension can't do: a break, an early return, a try/except around one item, or any of it that has to happen for its side effect rather than its value. A comprehension built purely for side effects, with its result thrown away, is a loop wearing the wrong clothes. Write for and let the reader see what is happening.
Nesting deserves its own warning. A comprehension inside another comprehension's formula is read outer-first and reasoned about inner-first, which is just the sort of thing that is fine while you're writing it and unpleasant three months later. Two statements are almost always better than one clever one.
Naming things the reader will meet
Two words appear constantly in discussions of this material and are rarely defined, which makes a lot of or else good explanations hard to follow.
A higher-order function is a function that takes a function as an arg or returns one. sorted is higher-order because of key=. So are map, filter, and each decorator you'll write. There's nothing more to the term than that.
A closure is a function that remembers a value from the scope where it was created, and keeps working after that scope has finished. The loop trap earlier on this page is a closure behaving just as given and not as expected: the lambdas remembered the variable rather than the value it held at the time.
Questions people ask about lambda, map and filter
Can a lambda have more than one statement? No. The body is a single formula. If you need a statement, you need a def.
Can a lambda have default args? Yes — lambda x, n=2: x ** n. And that is also the trick for capturing a loop variable by value.
Why does printing map(...) show an object? Because it's a lazy iterator. Wrap it in list() to see the items.
Is a comprehension faster than map? They're close. map(int, items) with an existing function is often slightly faster; map(lambda ..., items) is often slightly slower. Neither difference is a reason to choose one.
What does filter(None, items) do? Drops each falsy item. None in the function slot means "use the item's own truthiness".
Why can I not pickle a lambda? Pickling stores a ref by name and a lambda has none. That is why multiprocessing rejects them, and where functools.partial earns its place.
Do map and filter work on dicts? They work on any of it iterable, and iterating a dict gives its keys. Use d.items() when you want pairs.
lambda, map and filter: recap in one screen
- A lambda is a single-formula function. Use one as a
key= arg and write a def when it deserves a name. map and filter are lazy iterators. Consume them once, wrap in list() to keep them.- Prefer a comprehension by default.
map(existing_function, items) when it's just that shape. operator.itemgetter and attrgetter replace the most common lambdas and read better.reduce lives in functools because sum, max, any and all already cover almost each use of it.