Learn

Short lessons with real code you can edit and run on the page.

Lambda Functions in Python

Lesson 24 Python 3.14 Runs in your browser Updated
In short

A lambda is a small function written as a single expression, with no def and no name of its own. lambda n: n * 2 is a function that returns its argument doubled. Lambdas are mostly passed straight into other functions, such as the key of sorted().

Key facts

  • lambda n: n * 2 is a function that returns its argument doubled. The names before the colon are its parameters.
  • The body is one expression, and its value is returned automatically, so statements such as return or a for loop can't go inside.
  • sorted(people, key=lambda person: person[1]) sorts by the second item of each entry.
  • map() and filter() return iterators, so wrap them in list() to see the results.
  • PEP 8 recommends a def, not a lambda assigned to a variable, whenever a function needs a name.

What is a lambda function in Python?

A lambda is a small function written as a single expression, with no def and no name of its own. Python returns the expression's value automatically, so a lambda never contains return.

Python
def apply(func, value):
    return func(value)

def double(n):
    return n * 2

print(apply(double, 5))
print(apply(lambda n: n * 2, 5))
Output
10
10

Functions are values in Python, so you can pass one to another function the way you pass a number. apply() calls whatever function it receives, with value as the argument, and both calls give it a function that doubles its argument.

The first is defined with def and passed by its name alone, because parentheses would call it. The second is written right inside the call.

How do I write a lambda in Python?

Write lambda, the parameters, a colon and one expression. Commas separate several parameters, and a lambda with no parameters has nothing between lambda and the colon.

Python
add = lambda a, b: a + b
shout = lambda word: word.upper() + "!"
get_answer = lambda: 42

print(add(3, 4))
print(shout("hi"))
print(get_answer())
Output
7
HI!
42

You call a lambda the same way as any function, with parentheses. Naming lambdas like this is fine for trying the syntax, but PEP 8, Python's style guide, prefers a def for any function that gets a name, for a reason covered further down.

The body must be an expression, a piece of code that produces a value. Statements such as an assignment, an if block, a for loop or return do something without producing a value, so they can't go inside.

A call such as print(x) is an expression and works. So does a conditional expression such as "even" if n % 2 == 0 else "odd", because it produces a value.

How do I sort a list with a lambda in Python?

Pass the lambda as the key argument of sorted() or sort(). Python calls it once for each item and sorts the items by the values it returns.

Python
people = [("Ada", 36), ("Grace", 85), ("Linus", 21)]
by_age = sorted(people, key=lambda person: person[1])
print(by_age)
oldest_first = sorted(people, key=lambda person: person[1], reverse=True)
print(oldest_first)
Output
[('Linus', 21), ('Ada', 36), ('Grace', 85)]
[('Grace', 85), ('Ada', 36), ('Linus', 21)]

person[1] is the age in each tuple, so the list is sorted by age. Without a key, sorted() compares tuples item by item, so the names would decide. The list methods lesson passed key=str.lower the same way, and a lambda covers the cases where no ready-made function fits.

A lambda key also sorts a dictionary's items by value. items() gives each key with its value as a pair, and the lambda picks the value out of the pair.

Python
scores = {"Ada": 92, "Bob": 78, "Cy": 85}
for name, score in sorted(scores.items(), key=lambda pair: pair[1]):
    print(name, score)
Output
Bob 78
Cy 85
Ada 92

The sorting guide in the Python documentation covers key functions in more depth, including sorting by two values at once.

How do I use a lambda with max() and min()?

Pass it as the key, the same way as with sorted(). max() and min() then return the item that gives the largest or smallest key result, not the result itself.

Python
people = [("Ada", 36), ("Grace", 85), ("Linus", 21)]
print(max(people, key=lambda person: person[1]))
print(min(people, key=lambda person: person[1]))
words = ["kiwi", "banana", "fig"]
print(max(words, key=len))
Output
('Grace', 85)
('Linus', 21)
banana

The result is the whole tuple, so you get the name along with the age. The last line passes the built-in len directly, because no lambda is needed when a function that does the job already exists. If two items tie, max() and min() return the first one.

How do map() and filter() work with a lambda?

map() calls a function on every item, and filter() keeps the items for which the function returns a truthy value. Both return an iterator, which hands out each result once and is then used up, so wrap the call in list() to see them.

Python
numbers = [1, 2, 3, 4, 5]
doubled = map(lambda n: n * 2, numbers)
print(type(doubled))
print(list(doubled))
print(list(doubled))
evens = list(filter(lambda n: n % 2 == 0, numbers))
print(evens)
Output
<class 'map'>
[2, 4, 6, 8, 10]
[]
[2, 4]

The second list(doubled) is empty, because the first one used the iterator up. A list or a range can be looped over again and again, but an iterator can't.

A list comprehension does the same work and is often easier to read. [n * 2 for n in numbers] gives the same list as the map() call, and the list comprehension lesson covers the filtering form too.

What is the difference between lambda and def?

def makes a named function from any number of statements, and lambda makes an unnamed one from a single expression. Both produce the same kind of function object, and you call them the same way.

Python lambda compared with def
Questionlambdadef
What is it?An expression, such as lambda n: n * 2A statement with an indented body
What can the body hold?One expression, returned automaticallyAny number of statements, with return for the result
Name in tracebacks<lambda>The name after def
DocstringNo place for oneThe first line of the body
Use it forA short function passed straight into another callAnything you reuse, name or test

Anything a lambda can do, a def can do too, so a lambda is never required. It's a shorter way to write a throwaway function at the place where it's used.

When should you not use a lambda?

Don't use a lambda when the function needs a name, more than one statement or a docstring. PEP 8 says to write a def instead of assigning a lambda to a variable, because a def gives the function a real name for error messages.

Python
check = lambda n: 10 / n
print(check(0))
Output
Traceback (most recent call last):
  File "main.py", line 2, in <module>
    print(check(0))
          ~~~~~^^^
  File "main.py", line 1, in <lambda>
    check = lambda n: 10 / n
                      ~~~^~~
ZeroDivisionError: division by zero

A traceback has one File line for each step, starting with the main program. The second File line names the function only as <lambda>, so in a program with several lambdas, only the line number and the source line show which one failed. With def check(n), it would say in check.

If a lambda fits on one line only by packing in a conditional expression and calls inside calls, switch to def.

Common mistakes with lambda functions in Python

Lambdas usually go wrong in one of these three ways. Only the last one runs without an error, and it prints an object instead of the results.

  • SyntaxError: invalid syntax. The lambda's body starts with return. The expression is already the return value, so remove the word.
  • TypeError: sorted expected 1 argument, got 2. The lambda was passed without key=. sorted() takes only the list by position, so the key must be named.
  • Printing a map or filter object. print(map(...)) shows something like <map object at 0x...>. Wrap the call in list().

Run the two broken programs to see the messages, then fix them in the editor.

Python
double = lambda n: return n * 2
print(double(4))
Output
  File "main.py", line 1
    double = lambda n: return n * 2
                       ^^^^^^
SyntaxError: invalid syntax
Python
people = [("Ada", 36), ("Linus", 21)]
print(sorted(people, lambda person: person[1]))
Output
Traceback (most recent call last):
  File "main.py", line 2, in <module>
    print(sorted(people, lambda person: person[1]))
          ~~~~~~^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
TypeError: sorted expected 1 argument, got 2

Exercise

Sort products by price, the second item in each tuple, so the program prints [('pen', 3), ('book', 12), ('lamp', 25)]. The starter sorts by name, because without a key sorted() compares the tuples item by item, starting with the name.

Python
products = [("lamp", 25), ("pen", 3), ("book", 12)]
cheapest_first = sorted(products)
print(cheapest_first)
Output
Show the solution
products = [("lamp", 25), ("pen", 3), ("book", 12)]
cheapest_first = sorted(products, key=lambda product: product[1])
print(cheapest_first)

Quiz

This quiz has 5 questions. Pick an answer to see why it is right or wrong.

  1. 1What does this program print?

    area = lambda width, height: width * height
    print(area(3, 4))
  2. 2What does this program print?

    words = ["pear", "fig", "banana"]
    print(sorted(words, key=lambda w: len(w)))
  3. 3What can the body of a lambda contain?

  4. 4What does this program print?

    nums = [1, 2, 3, 4]
    print(list(filter(lambda n: n > 2, nums)))
  5. 5Why does PEP 8 recommend def over assigning a lambda to a variable?

Frequently asked questions

What is a lambda function in Python?
A lambda is a small unnamed function written as a single expression after the keyword lambda. It returns the value of that expression automatically and is usually passed straight into another function, such as the key of sorted().
Why is it called lambda?
The name comes from the lambda calculus, a system for describing functions that the mathematician Alonzo Church introduced in the 1930s. Lisp adopted the word for unnamed functions, and Python's lambda follows that tradition.
Can a lambda take more than one argument?
Yes. List the parameters before the colon, separated by commas the same way as in a def line, and pass that many arguments in the call. Default values, *args and **kwargs work in a lambda too.
Can a lambda use if and else?
Yes, through a conditional expression such as lambda n: "even" if n % 2 == 0 else "odd". An if statement with an indented block can't go inside a lambda, because the body must be a single expression.
Can a lambda have more than one line?
Not the way a def can. The body is a single expression, which can wrap onto several lines inside parentheses but can't hold statements. Once a function needs more than one step, write a def.
What is the difference between lambda and def in Python?
def creates a named function whose body can hold any number of statements and returns a value with return. lambda creates an unnamed function from a single expression whose value is returned automatically, and both produce the same kind of function object.
When should I use a lambda in Python?
Use one for a short function that is passed straight into another call and used nowhere else, such as a sort key. When the function needs a name, a docstring or more than one statement, write a def.