A lambda function is a small, anonymous function written in a single expression. Instead of defining a full function with def, you can write lambda x: x * 2 right where you need it. Lambdas are most useful when you pass a short function to another function, for example to tell sorted() how to order items.
In this tutorial, you’ll learn the lambda syntax, how to use lambdas with Python’s built-in functions, how they capture variables, and when a regular function is the better choice.
Key terms used in this article:
- Lambda function: An anonymous function created with the
lambdakeyword. It can contain only one expression. - Anonymous function: A function without a name.
- Higher-order function: A function that takes another function as an argument or returns one, such as
sorted(),map(), andfilter(). - Key function: A function that tells
sorted(),min(), ormax()what value to compare for each item. - Closure: An inner function that remembers variables from the scope where it was created.
Table of contents
- Lambda syntax
- Calling a lambda immediately
- Lambda arguments
- Conditional logic in a lambda
- What lambdas cannot do
- Using lambda with sorted()
- Using lambda with min() and max()
- Using lambda with map()
- Using lambda with filter()
- Using lambda with reduce()
- Lambda vs. list comprehension
- Returning a lambda from a function (closures)
- Lambdas in dictionaries (dispatch tables)
- The late-binding trap
- Alternatives to lambda in the standard library
- When to use lambda and when to use def
- Common mistakes
- Practice exercises
- Summary
Lambda syntax
lambdais the keyword that creates the function.argumentsis a comma-separated list of parameters. It can be empty.expressionis a single expression. Its value is returned automatically, so there’s noreturnkeyword.
Here’s the same function written with def and with lambda:
Output:
25 25 <lambda>
Both functions do the same thing. The lambda’s name shows as <lambda>, because a lambda is anonymous.
Style tip: Assigning a lambda to a variable, as in square_lambda = lambda x: x * x, works but is discouraged by PEP 8. If a function needs a name, use def. Lambdas are meant to be used inline, as arguments to other functions.
Calling a lambda immediately
You can define and call a lambda in one expression. This is mostly useful for understanding how lambdas work:
Output:
7
Lambda arguments
Lambdas support the same kinds of parameters as regular functions.
Output:
Hello! 6 16 1024 Jessa Doe 10 name=Kelly, age=30
Conditional logic in a lambda
A lambda can’t contain an if statement, but it can use a conditional expression (value_if_true if condition else value_if_false):
Output:
even odd A B C
Nested conditional expressions get hard to read quickly. If you need more than two branches, a def function with if/elif is clearer.
What lambdas cannot do
Because a lambda is limited to one expression, you can’t use statements inside it:
- No
return,pass,assert, orraisestatements - No assignments with
=(the walrus operator:=is allowed but rarely a good idea) - No loops written as statements (comprehensions are fine, because they’re expressions)
- No docstrings or type annotations
Output:
[1, 4, 9, 16, 25]
Using lambda with sorted()
The most common use of a lambda is as a key function. sorted(), list.sort(), min(), and max() call the key function on each item and compare the results.
Output:
['Cherry', 'apple', 'banana', 'date'] ['apple', 'banana', 'Cherry', 'date'] ['date', 'apple', 'banana', 'Cherry'] ['banana', 'apple', 'date', 'Cherry']
Sorting lists of tuples and dictionaries
Output:
[('Kelly', 95), ('Brad', 95), ('Jessa', 88), ('Emma', 79)]
[('Brad', 95), ('Kelly', 95), ('Jessa', 88), ('Emma', 79)]
['Emma', 'Jessa', 'Kelly']
Returning a tuple from the key function sorts by several fields at once. The negative sign reverses the order for a numeric field only.
Sorting a dictionary by value
Output:
{'bananas': 12, 'apples': 30, 'cherries': 45}
Using lambda with min() and max()
Output:
('mouse', 25)
('laptop', 1200)
elephant
Using lambda with map()
map(function, iterable) applies a function to every item and returns a lazy iterator. Wrap it in list() to see the results:
Output:
[11.8, 29.5, 47.2] ['Jessa', 'Kelly', 'Emma'] [11, 22, 33]
Using lambda with filter()
filter(function, iterable) keeps only the items for which the function returns a truthy value:
Output:
[8, 22, 40] ['python', 'java', 'go']
Using lambda with reduce()
functools.reduce() combines all items into a single value by applying a two-argument function cumulatively:
Output:
120 5 10
For simple cases, built-ins such as sum(), max(), and math.prod() are clearer than reduce().
Lambda vs. list comprehension
map() and filter() with a lambda can often be replaced by a list comprehension, which most Python developers find easier to read:
Output:
[4, 16, 36] [4, 16, 36]
Use a comprehension when you’re building a new list. Use map() when you already have a named function, as in map(str.upper, names).
Returning a lambda from a function (closures)
A function can create and return a lambda. The lambda remembers the variables from the function that created it. This is called a closure:
Output:
20 30
Lambdas in dictionaries (dispatch tables)
A dictionary of lambdas can replace a long if/elif chain:
Output:
12 + 4 = 16 12 - 4 = 8 12 * 4 = 48 12 / 4 = 3.0 undefined
The late-binding trap
Lambdas look up variables when they’re called, not when they’re created. This causes a classic bug when you create lambdas in a loop:
Output:
[2, 2, 2]
All three lambdas see the final value of i, which is 2. To capture the current value, use a default argument, which is evaluated when the lambda is created:
Output:
[0, 1, 2]
Alternatives to lambda in the standard library
The operator module has ready-made functions for the most common lambdas. They’re faster and often clearer:
| Lambda | operator equivalent |
|---|---|
lambda x: x[1] | operator.itemgetter(1) |
lambda x: x["name"] | operator.itemgetter("name") |
lambda obj: obj.age | operator.attrgetter("age") |
lambda a, b: a + b | operator.add |
lambda a, b: a * b | operator.mul |
lambda s: s.lower() | str.lower |
Output:
[('Emma', 79), ('Jessa', 88), ('Kelly', 95)]
['Apple', 'banana', 'cherry']
When to use lambda and when to use def
| Use a lambda when | Use def when |
|---|---|
| The function is a short, one-line expression | The logic needs several statements or branches |
You pass it once as an argument (key=, map(), filter()) | You call it in several places |
| The meaning is obvious from the expression | It needs a descriptive name, a docstring, or type hints |
You want readable tracebacks (lambdas show up as <lambda>) |
Common mistakes
- Calling the lambda instead of passing it.
sorted(items, key=(lambda x: x[1])(items))is wrong. Pass the function itself:key=lambda x: x[1]. - Forgetting
list()aroundmap()orfilter(). In Python 3, both return lazy iterators, soprint(map(...))shows<map object ...>. - Using
returninside a lambda.lambda x: return xis aSyntaxError. The expression’s value is returned automatically. - Late binding in loops. Use
lambda x=x: ...to capture the current loop value. - Overusing lambdas. If you need to read a lambda twice to understand it, turn it into a named function.
Practice exercises
Exercise 1: Sort a list of words by their number of vowels, fewest first.
Output:
['sky', 'rhythm', 'apple', 'banana', 'education']
Exercise 2: Use filter() and a lambda to keep only the palindromes in a list.
Output:
['level', 'radar', 'noon']
Exercise 3: Convert a list of Celsius temperatures to Fahrenheit using map() and a lambda.
Output:
[32.0, 70.7, 98.6, 212.0]
Exercise 4: Find the student with the highest average score.
Output:
Kelly
Summary
- A lambda is an anonymous, single-expression function:
lambda args: expression. - The expression’s value is returned automatically. Statements such as
return, loops, and assignments aren’t allowed. - Lambdas are most useful as short key functions for
sorted(),min(), andmax(), and as arguments tomap(),filter(), andreduce(). - Lambdas can capture variables from the enclosing scope, but they look them up when called. Use default arguments to capture loop values.
- Prefer list comprehensions over
map()/filter()with lambdas, and preferdeffor anything longer than one simple expression.
Also, See:

Leave a Reply