# Python Lambda Functions

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

Author: [Flavio Copes](https://flaviocopes.com/about/) | Published: 2021-01-07 | Updated: 2026-08-07 | Topics: [Python](https://flaviocopes.com/tags/python/) | Canonical: https://flaviocopes.com/python-lambda-functions/

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

In [Python](https://flaviocopes.com/python-introduction/) they are defined using the `lambda` keyword:

```python
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:

```python
lambda num : num * 2
```

Lambda functions can accept more arguments:

```python
lambda a, b : a * b
```

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

```python
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:

```python
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:

```python
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:

```python
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:

```python
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`.
