# Python Lambda Functions: Anonymous Functions With lambda

Source: https://devdocs10.com/articles/python/python-lambda  
By Murat Bo · Published 2026-12-01 · DevDocs10 (https://devdocs10.com)

Python `lambda` functions are small anonymous functions that return one expression. They are useful when you need a short function for sorting, filtering, mapping, or passing as an argument to another function. This article explains how they work, when they help, and where they become hard to read.

> **Difficulty:** Beginner
>
> **Helpful to know first:** basic Python syntax, variables, functions with `def`, and how function arguments work.

## How Python Lambda Functions Work

A `lambda` function is a function expression, not a statement. It creates a function object just like `def`, but it must fit on one expression and it returns that expression automatically. You use it when the function is small, short-lived, and easier to read inline than as a separate named function.

The basic form is:

```python
lambda arguments: expression
```

The value of the expression becomes the return value. For example, this lambda adds two numbers:

```python
add = lambda a, b: a + b
print(add(2, 3))  # Output: 5
```

This works the same way as a small `def` function, but with less syntax. The important limitation is that a lambda can only contain a single expression, not multiple statements.

## Common Lambda Patterns in Real Python Code

### Sorting a list by a custom rule

One of the most common uses for `lambda` is as a `key` function for `sorted()` or `list.sort()`. The lambda tells Python how to rank each item.

```python
people = [
    ("Ada", 36),
    ("Grace", 28),
    ("Linus", 33)
]

by_age = sorted(people, key=lambda person: person[1])
print(by_age)  # Output: [('Grace', 28), ('Linus', 33), ('Ada', 36)]
```

The lambda receives one item at a time and returns the value used for comparison. Here, it returns the age from each tuple.

### Filtering data with a quick test

Another common use is with `filter()`. The lambda returns `True` or `False` for each item.

```python
numbers = [1, 2, 3, 4, 5]
evens = list(filter(lambda n: n % 2 == 0, numbers))
print(evens)  # Output: [2, 4]
```

The lambda expression is short enough that the condition is readable inline. If the logic becomes more complex, a named function is usually clearer.

### Transforming values with map

`map()` applies a function to each item in an iterable. A lambda is a quick way to define the transformation right where you need it.

```python
temps_c = [0, 20, 37]
temps_f = list(map(lambda c: c * 9 / 5 + 32, temps_c))
print(temps_f)  # Output: [32.0, 68.0, 98.6]
```

This example also shows an important detail: the result is often a float, not an int, because division with `/` always produces a floating-point number in Python.

### Using lambda in a small GUI or callback style API

Many APIs ask you to give them a function to run later. A lambda can be useful when the callback is tiny and does not deserve a separate function name.

```python
def make_greeting(name, formatter):
    return formatter(name)

result = make_greeting("Mina", lambda text: f"Hello, {text}!")
print(result)  # Output: Hello, Mina!
```

Here the lambda is only used once, so naming a separate function would add more code without making the program clearer.

## How Lambda Differs From def

A lambda and a function written with `def` both create callable objects. The difference is mostly about syntax, readability, and what the body can contain. A `def` function can have many statements, docstrings, type annotations, and multiple return paths. A lambda is restricted to a single expression.

| Feature | lambda | def |
| --- | --- | --- |
| Name | Usually anonymous unless assigned to a variable | Explicit function name |
| Body | One expression only | Any number of statements |
| Readability | Best for tiny operations | Best for reusable logic |
| Docstring | Not practical | Supported |
| Annotations | Not part of lambda syntax | Supported |

For example, these two functions do the same thing, but the `def` version is easier to extend:

```python
double_lambda = lambda x: x * 2

def double_def(x):
    return x * 2

print(double_lambda(4))
print(double_def(4))  # Output: 8\n8
```

Use `lambda` when the code stays tiny and local. Use `def` when the logic has names, branches, error handling, or anything that would make one line hard to read.

## How Lambda Functions Behave in Detail

### Lambda closes over variables, not values

A lambda can refer to variables from the surrounding scope. That is called a closure. The lambda does not copy the value immediately in the way many beginners expect; it looks up the variable when it runs.

```python
funcs = []

for i in range(3):
    funcs.append(lambda: i)

for func in funcs:
    print(func())  # Output: 2\n2\n2
```

All three lambdas share the same `i` variable, and by the time they run the loop has finished. If you want each lambda to keep its own current value, bind it as a default argument:

```python
funcs = []

for i in range(3):
    funcs.append(lambda i=i: i)

for func in funcs:
    print(func())  # Output: 0\n1\n2
```

This is one of the most important lambda gotchas in Python.

### Lambda cannot contain statements

You cannot put `return`, `if`, assignment, or a loop inside a lambda body. The body must be a single expression that produces a value.

> The expression can be complex, but if you need multiple steps, the code is usually clearer as a named function.

```bash
# This is valid
format_price = lambda amount: f"${amount:.2f}"

# This would be invalid:
# bad = lambda x: if x > 0: x else: -x
```

For control flow, use a conditional expression inside the lambda, such as `x if x > 0 else -x`. If the logic becomes difficult to scan, switch to `def`.

### The lambda object has a generated name

If you inspect a lambda, Python usually shows its name as `<lambda>`. That is fine for short-lived callbacks, but it is less helpful in stack traces and debugging than a real function name.

```python
square = lambda x: x * x
print(square.__name__)  # Output: <lambda>
```

That is another reason to prefer `def` for important reusable logic.

## Predict the Output

### Late binding in a loop

```python
funcs = []
for i in range(3):
    funcs.append(lambda: i)

for func in funcs:
    print(func())
```

What does this print?

**Answer:**

It prints:

```python
2
2
2
```

Each lambda refers to the same `i` variable from the loop. By the time the lambdas run, `i` has the final value `2`. This is called late binding.

### Default arguments capture the current value

```python
funcs = []
for i in range(3):
    funcs.append(lambda i=i: i)

for func in funcs:
    print(func())
```

What does this print?

**Answer:**

It prints:

```python
0
1
2
```

Each lambda stores its own default value for `i`, so the functions do not share one changing loop variable.

## Find the Bug

Someone wants to square every number and keep the results in a new list. The code looks short and neat, but it does not do what the author expects. Find the bug.

```python
numbers = [1, 2, 3]
squares = [lambda x: x * x for x in numbers]
print([func() for func in squares])
```

**Answer:**

The bug is that the code stores lambda functions instead of storing the squared numbers. The list comprehension creates three function objects, and the final print calls them later. Because the lambdas close over the same loop variable, they all use the last value of `x`.

**Fix:** Compute the values directly, or bind the value in the lambda if you really want functions.

```python
numbers = [1, 2, 3]
squares = [x * x for x in numbers]
print(squares)  # Output: [1, 4, 9]
```

The corrected version works because it builds the list of results directly instead of creating delayed functions.

## Common Mistakes With Lambda Functions

### Trying to put statements inside a lambda

Beginners often try to write a multi-step function inside `lambda`. Python does not allow that, because lambda bodies can only be expressions.

**Problem:** This code tries to use an `if` statement inside a lambda, so Python raises a syntax error.

```python
sign = lambda n: if n > 0: 1 else -1
```

**Fix:** Use a conditional expression, or write a normal function with `def` if the logic is not tiny.

```python
sign = lambda n: 1 if n > 0 else -1
print(sign(-3))  # Output: -1
```

The fixed version works because a conditional expression is still one expression, which lambda allows.

### Expecting lambda to freeze loop values automatically

A lambda inside a loop often surprises people because it keeps a reference to the variable, not a copy of its value.

**Problem:** The lambdas all use the same final loop value, so every function returns the same number.

```python
funcs = []
for i in range(3):
    funcs.append(lambda: i)

print([func() for func in funcs])
```

**Fix:** Bind the current value as a default argument.

```python
funcs = []
for i in range(3):
    funcs.append(lambda i=i: i)

print([func() for func in funcs])  # Output: [0, 1, 2]
```

The default argument stores the value at creation time, so each lambda remembers its own number.

### Using lambda for code that needs a name

Sometimes the code works, but the choice of lambda makes debugging harder. If the function is reused, has branches, or needs a clear name in traces, use `def` instead.

**Problem:** This lambda is harder to read and harder to extend than a named function, especially once error handling or extra formatting is added.

```python
format_user = lambda user: f"{user['name'].title()} ({user['role']})"
```

**Fix:** Use a named function when the logic is meaningful enough to deserve one.

```python
def format_user(user):
    return f"{user['name'].title()} ({user['role']})"
```

The named version is easier to understand, test, and expand later.

## When to Use Lambda and When to Use def Instead

Use `lambda` when the function is tiny, local, and obviously readable inline. Use `def` when the logic matters enough that a name will help future readers.

| Situation | Better choice | Why |
| --- | --- | --- |
| One-line sort key | lambda | Short, local, and common with `sorted()` |
| Small filter or map expression | lambda | Clear when the logic is simple |
| Reusable business rule | def | Needs a name, comments, and possibly tests |
| Multiple branches or validation | def | Lambda cannot contain statements |
| Debugging important logic | def | Better function names in tracebacks |

One common mistake is to treat lambda as the “Pythonic” default. It is not. A short named function is often more readable than a clever lambda. The main point is clarity, not brevity.

## Interview Questions About Python Lambda Functions

### Why use lambda if def can do the same job?

`lambda` is useful when you need a small function in place and giving it a separate name would add clutter. It is not a faster or more powerful version of `def`; it is mostly a syntax convenience.

### Can a lambda have multiple arguments?

Yes. A lambda can take any number of arguments, including default values. The body still must be one expression.

### Why does lambda in a loop act strangely?

Because lambdas capture variables by reference, not by copying the current value. If you create lambdas in a loop, they often all see the final loop value unless you bind the value with a default argument.

## Try It Yourself

Write a small program that uses lambda functions to process a list of temperatures.

- Create a list of Celsius values: `[0, 10, 20, 30]`.
- Use one lambda to convert each value to Fahrenheit.
- Use another lambda to keep only temperatures at or above freezing in Fahrenheit.
- Print both results.

Expected output:

```python
[32.0, 50.0, 68.0, 86.0]
[32.0, 50.0, 68.0, 86.0]
```

Hint: use `map()` for the conversion and `filter()` for the test.

**Solution:**

```python
temps_c = [0, 10, 20, 30]

to_fahrenheit = lambda c: c * 9 / 5 + 32
is_freezing_or_warmer = lambda f: f >= 32

temps_f = list(map(to_fahrenheit, temps_c))
safe_temps = list(filter(is_freezing_or_warmer, temps_f))

print(temps_f)
print(safe_temps)  # Output: [32.0, 50.0, 68.0, 86.0]\n[32.0, 50.0, 68.0, 86.0]
```

## Summary

- A `lambda` is an anonymous function with one expression.
- It returns the expression result automatically.
- It is common in `sorted()`, `map()`, `filter()`, and other callback-style code.
- It cannot contain statements such as assignment, `return`, or a multi-line `if` block.
- Be careful with closures in loops, because lambdas capture variables, not copied values.
- Use `def` when the logic is longer, reusable, or needs a clear name.

Next, learn about `Python closures` and how nested functions keep access to variables from their enclosing scope.
