Lambda Functions in Python
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 * 2is 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
returnor a for loop can't go inside. sorted(people, key=lambda person: person[1])sorts by the second item of each entry.map()andfilter()return iterators, so wrap them inlist()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.
def apply(func, value):
return func(value)
def double(n):
return n * 2
print(apply(double, 5))
print(apply(lambda n: n * 2, 5))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.
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())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.
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)[('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.
scores = {"Ada": 92, "Bob": 78, "Cy": 85}
for name, score in sorted(scores.items(), key=lambda pair: pair[1]):
print(name, score)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.
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))('Grace', 85)
('Linus', 21)
bananaThe 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.
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)<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.
| Question | lambda | def |
|---|---|---|
| What is it? | An expression, such as lambda n: n * 2 | A statement with an indented body |
| What can the body hold? | One expression, returned automatically | Any number of statements, with return for the result |
| Name in tracebacks | <lambda> | The name after def |
| Docstring | No place for one | The first line of the body |
| Use it for | A short function passed straight into another call | Anything 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.
check = lambda n: 10 / n
print(check(0))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 zeroA 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 inlist().
Run the two broken programs to see the messages, then fix them in the editor.
double = lambda n: return n * 2
print(double(4)) File "main.py", line 1
double = lambda n: return n * 2
^^^^^^
SyntaxError: invalid syntaxpeople = [("Ada", 36), ("Linus", 21)]
print(sorted(people, lambda person: person[1]))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 2Exercise
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.
products = [("lamp", 25), ("pen", 3), ("book", 12)]
cheapest_first = sorted(products)
print(cheapest_first)
[('pen', 3), ('book', 12), ('lamp', 25)]
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.
-
1What does this program print?
area = lambda width, height: width * height print(area(3, 4))The lambda takes two parameters and returns their product, and 3 * 4 is 12. A lambda can take as many parameters as a def function.
-
2What does this program print?
words = ["pear", "fig", "banana"] print(sorted(words, key=lambda w: len(w)))The key gives each word its length, 4, 3 and 6, and sorted() orders the words by those numbers. Without the key they would be sorted alphabetically.
-
3What can the body of a lambda contain?
A lambda body is a single expression, and its value is returned automatically. Statements such as return, assignments with = and for loops need a def.
-
4What does this program print?
nums = [1, 2, 3, 4] print(list(filter(lambda n: n > 2, nums)))filter() keeps the items for which the lambda returns a truthy value, so only 3 and 4 remain. list(map(...)) with the same lambda would give [False, False, True, True].
-
5Why does PEP 8 recommend def over assigning a lambda to a variable?
Both create the same kind of function and run at the same speed. The difference is the name, which a def gives the function and a traceback then shows instead of <lambda>.























