Skip to content
FLAVIO COPES
flaviocopes.com

Python Lambda Functions

By

Learn how lambda functions work in Python: tiny anonymous functions with the lambda keyword and a single expression, often used with map() and filter().

~~~

Lambda functions (also called anonymous functions) are tiny functions that have no name and only have one expression as their body.

In Python they are defined using the lambda keyword:

lambda <arguments> : <expression>

The body must be a single expression. Expression, not a statement.

This difference is important. An expression returns a value, a statement does not.

The simplest example of a lambda function is a function that doubles the value of a number:

lambda num : num * 2

Lambda functions can accept more arguments:

lambda a, b : a * b

Lambda functions cannot be invoked directly, but you can assign them to variables:

multiply = lambda a, b : a * b

print(multiply(2, 2)) # 4

That said, if you find yourself naming a lambda, a regular def function is clearer. The point of a lambda is to stay anonymous.

Where lambdas shine

The utility of lambda functions comes when combined with other Python functionality, for example in combination with map(), filter() and sorted(). These functions accept another function as an argument, and a lambda lets you write that function inline, right where it’s used.

map() applies the function to every element:

prices = [3.5, 1.2, 8.9]
doubled = list(map(lambda p: p * 2, prices))
# [7.0, 2.4, 17.8]

filter() keeps the elements for which the function returns true:

numbers = [1, 2, 3, 4, 5, 6]
even = list(filter(lambda n: n % 2 == 0, numbers))
# [2, 4, 6]

Both map() and filter() return an iterator, so we wrap the result in list() to see the values.

My favorite use case is the key argument of sorted(). Here we sort a list of items by their price:

items = [('bread', 1.2), ('milk', 0.9), ('eggs', 3.4)]
by_price = sorted(items, key=lambda item: item[1])
# [('milk', 0.9), ('bread', 1.2), ('eggs', 3.4)]

The lambda tells sorted() which value to compare, without defining a separate function for a one-line job.

A common error

Remember the expression rule. If you try to put a statement in the body, like an assignment, Python refuses to run it:

double = lambda num : num = num * 2
# SyntaxError: cannot assign to lambda

When your logic needs statements, or more than one line, switch to a regular function defined with def.

Tagged: Python · All topics
~~~

Related posts about python: