Python16 min read

Python Lambda Functions

Use lambda for short one-line logic, especially sorting and quick transformations, without hurting readability.

Michael Brown
August 22, 2025
4.1k187

A lambda is a small anonymous function written in one line. It is useful when your logic is short and you do not want to define a full function with def.

Important rule:
If the lambda becomes long, write a normal function.

## Lambda basics

```python
add = lambda x, y: x + y
print(add(3, 5))
```

Expected output:

```
8
```

## Most common real use: sorting

```python
people = [
    {"name": "Tom", "age": 25},
    {"name": "Sarah", "age": 22},
    {"name": "Mike", "age": 30}
]

people.sort(key=lambda person: person["age"])
print(people)
```

Expected output:

```
[{'name': 'Sarah', 'age': 22}, {'name': 'Tom', 'age': 25}, {'name': 'Mike', 'age': 30}]
```

## map and filter examples

```python
numbers = [1, 2, 3, 4]
doubled = list(map(lambda x: x * 2, numbers))
print(doubled)
```

Expected output:

```
[2, 4, 6, 8]
```

```python
ages = [15, 22, 18, 30, 12]
adults = list(filter(lambda age: age >= 18, ages))
print(adults)
```

Expected output:

```
[22, 18, 30]
```

## Graph: lambda usage pattern

```mermaid
flowchart LR
  A[Data] --> B[sort/map/filter]
  B --> C[lambda expression]
  C --> D[Result]
```

In the next lesson, you will learn try/except, which helps your program handle errors without crashing.
#Python#Intermediate#Functions