---
title: "Python Lambda Functions: When to Use Them, 10 Examples"
description: "Lambda functions in Python explained: the anatomy, the key argument, map and filter, when not to use them, and 10 tested examples with output."
slug: python-lambda-functions
canonical: https://learn.modernagecoders.com/blog/python-lambda-functions/
date: 2026-07-03
dateModified: 2026-07-03
category: "Programming"
tags: ["Python", "Lambda", "Functions", "Intermediate Python", "Clean Code"]
keywords: ["lambda function python", "python lambda", "anonymous function python", "sorted key lambda python", "map filter lambda python", "lambda vs def python", "sort by value lambda"]
readTime: "7 min read"
author: "Modern Age Coders"
---
# Python Lambda Functions: When to Use Them, 10 Examples

> What lambdas are, where they genuinely belong, and when to write a def instead, with 10 tested examples.

![Python lambda functions explained with 10 tested examples](/images/blog/python-lambda-functions/00-hero.png)

*By Modern Age Coders · 2026-07-03 · 7 min read*

Somewhere in every Python codebase sits a line like sorted(data, key=lambda x: x[1]), and every beginner who meets it has the same two questions: what is that lambda thing, and why did nobody just write a normal function? This guide answers both, honestly.

A **lambda function** is a small, anonymous function written as a single expression. It exists for one reason: sometimes you need a tiny throwaway function for exactly one moment, usually to tell another function like sorted(), max(), or filter() how to treat each item, and defining a full def for that moment is more ceremony than the job deserves.

Below are 10 tested examples, from your first lambda to sorting by two fields at once, plus the part most tutorials skip: when a lambda is the wrong choice. If functions in general still feel new, take a lap through [Python for beginners](/blog/python-for-beginners) first.

## The Anatomy of a Lambda

Three parts: the lambda keyword, the arguments, and one expression whose value is returned automatically. That single-expression rule is the defining constraint. No statements, no loops, no multiple lines. It is a function distilled to one thought.

![Anatomy of a Python lambda function: the lambda keyword, the arguments, and a single expression that is returned automatically](/images/blog/python-lambda-functions/01-anatomy.png)

*One keyword, the arguments, one expression. The return is implied.*

Here is the same function written both ways. They behave identically; the difference is purely where and how briefly you need it.

![The same doubling function written with def and as a lambda in Python, behaving identically](/images/blog/python-lambda-functions/02-def-vs-lambda.png)

*Same function, two outfits. def for functions with a life, lambda for functions with a moment.*

### 1. Your first lambda

A lambda is a function squeezed into an expression: arguments before the colon, one expression after, and the result comes back automatically, no return needed. We name it here only so you can see it work; in real code, lambdas usually stay anonymous.

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

print(double(5))
print(double(21))
```

```text
10
42
```

### 2. Two arguments, same idea

Lambdas take multiple arguments exactly like def functions.

```python
area = lambda length, width: length * width

print(area(5, 3))
print(area(12, 4))
```

```text
15
48
```

## Where Lambdas Actually Live: the key Argument

Examples 1 and 2 exist to teach the syntax, but you will almost never assign a lambda to a name in real code. The genuine habitat of the lambda is the key argument, where it acts as a lens: it tells sorted(), max(), and min() what to look at when comparing items.

### 3. Sort words by length

This is the lambda's true home: the key argument of sorted(). The lambda tells sorted() what to measure about each item, here the word's length, and the ordering follows that measurement.

```python
words = ["python", "go", "javascript", "java", "c"]

by_length = sorted(words, key=lambda w: len(w))

print(by_length)
```

```text
['c', 'go', 'java', 'python', 'javascript']
```

![How the key argument works in Python sorted: the lambda measures each item and the ordering follows those measurements](/images/blog/python-lambda-functions/03-key-lens.png)

*sorted() never compares your items directly. It compares what the key lambda returns for each.*

### 4. Sort pairs by the second value

Records often arrive as tuples. The lambda reaches into each pair and picks the field to sort by, here the marks at position 1, highest first.

```python
results = [("Asha", 92), ("Rohan", 85), ("Meera", 96), ("Zoya", 78)]

ranked = sorted(results, key=lambda pair: pair[1], reverse=True)

print(ranked)
```

```text
[('Meera', 96), ('Asha', 92), ('Rohan', 85), ('Zoya', 78)]
```

### 5. Sort a dictionary by its values

The same trick sorts dictionaries. Take the items, point the lambda at position 1, and rebuild.

```python
marks = {"maths": 92, "english": 75, "science": 88}

ranked = dict(sorted(marks.items(), key=lambda item: item[1], reverse=True))

print(ranked)
```

```text
{'maths': 92, 'science': 88, 'english': 75}
```

### 6. Find the top item with max()

max() and min() accept the same key argument, which turns them into instant judges of anything.

```python
results = [("Asha", 92), ("Rohan", 85), ("Meera", 96)]

topper = max(results, key=lambda pair: pair[1])
longest = max(["go", "python", "javascript"], key=lambda w: len(w))

print("Topper :", topper)
print("Longest:", longest)
```

```text
Topper : ('Meera', 96)
Longest: javascript
```

## map() and filter(), With an Honest Note

Lambdas also pair with map() and filter(), and you should be able to read those combinations because older code is full of them. Worth knowing: modern Python style often prefers a [list comprehension](/blog/python-list-comprehension-explained) for the same jobs, [p * 2 for p in prices] instead of map. Both are correct; comprehensions are simply what you will see recommended more today.

### 7. Transform a list with map()

map() applies a function to every item. With a lambda, the whole transformation fits on one line. The list() call around it turns the lazy map object into a real list.

```python
prices = [120, 250, 80]

with_gst = list(map(lambda p: round(p * 1.18), prices))

print(with_gst)
```

```text
[142, 295, 94]
```

### 8. Filter a list with filter()

filter() keeps only the items for which the lambda returns True.

```python
numbers = [12, 7, 20, 3, 18, 9]

evens = list(filter(lambda n: n % 2 == 0, numbers))

print(evens)
```

```text
[12, 20, 18]
```

## Two Sharper Tricks

Two closing patterns worth keeping: a conditional expression inside a lambda, and the tuple trick for sorting by more than one field.

### 9. A conditional inside a lambda

A lambda body must be a single expression, and a conditional expression qualifies. This is as much logic as a lambda should ever hold.

```python
grade = lambda m: "pass" if m >= 40 else "fail"

print([grade(m) for m in [35, 72, 48, 91]])
```

```text
['fail', 'pass', 'pass', 'pass']
```

### 10. Sort by two things at once

Return a tuple from the lambda and Python sorts by the first field, breaking ties with the second: here grade first, then name alphabetically.

```python
students = [("Rohan", 8), ("Asha", 7), ("Meera", 8), ("Zoya", 7)]

ordered = sorted(students, key=lambda s: (s[1], s[0]))

print(ordered)
```

```text
[('Asha', 7), ('Zoya', 7), ('Meera', 8), ('Rohan', 8)]
```

## When Not to Use a Lambda

The lambda's limits are features, not flaws, and respecting them is what separates tidy code from clever code. If the logic needs two steps, a name that explains itself, or will be used in more than one place, write a def. Python's own style guide, PEP 8, explicitly advises def over assigning a lambda to a variable, because grade = lambda m: ... gives you the worst of both: an anonymous function that now has a name, but no proper signature or docstring.

![When to use a lambda in Python versus when to write a def function](/images/blog/python-lambda-functions/04-use-avoid.png)

*A lambda is for a moment. A def is for a job.*

## Mistakes That Catch Everyone

- **Trying to put statements inside:** lambda x: print(x); x + 1 is a syntax error. One expression only.
- **Forgetting list() around map or filter:** printing map(...) directly shows a map object, not your results.
- **Writing an if without an else:** inside a lambda the conditional is an expression, so the else is compulsory.
- **Stuffing complex logic in:** if your lambda needs a deep breath to read aloud, it wanted to be a def.
- **Assigning lambdas to names as a habit:** fine for a quick demo, but PEP 8 says use def, and it is right.

> **The reading trick**

> Read key=lambda pair: pair[1] as by the second value. Read key=lambda w: len(w) as by length. The word by translates every key lambda you will ever meet into plain English.

---

## Frequently Asked Questions

**What is a lambda function in Python?**

A small anonymous function defined in a single expression: lambda arguments: expression. The expression's value is returned automatically. Lambdas are typically passed straight into functions like sorted(), max(), map(), and filter() rather than being named.

**What is the difference between lambda and def?**

def creates a named function that can hold many statements, a docstring, and reusable logic. A lambda holds exactly one expression and usually has no name. Use def for anything with a life beyond one line; use lambda for a small function needed in exactly one place.

**Why is lambda used in sorted()?**

sorted() accepts a key function that it calls on every item, and it orders items by those results instead of the items themselves. A lambda is the lightest way to say sort by length or sort by the second field right at the call site.

**Can a lambda have if else?**

Yes, as a conditional expression: lambda m: "pass" if m >= 40 else "fail". The else part is compulsory, because the lambda must always produce a value. Full if statements with blocks are not allowed.

**Can a lambda have multiple lines or statements?**

No. A lambda body is one expression, full stop. No assignments, no loops, no statements. The moment your logic needs more, that is Python nudging you toward def, and you should take the hint.

**Is lambda faster than a normal function?**

No, they compile to essentially the same thing and run at the same speed. Choose between them for readability, not performance.

**Should I use map and filter or list comprehensions?**

Both work, and you must be able to read both. Modern Python style generally prefers comprehensions: [p * 2 for p in prices] reads more directly than list(map(lambda p: p * 2, prices)). map and filter still shine when you already have a named function to apply.

## A Small Tool, Used Precisely

That is the lambda: not a rite of passage, just a small tool with a precise grip. You will use it most inside sorted() and max(), you will read it everywhere in data code, where libraries like pandas lean on it constantly, and you now know exactly when to put it down and write a def instead. That path into data work is what our [Python, AI and ML track](/master-ai-ml-python-java) is built around.

Round out this level with [list comprehensions](/blog/python-list-comprehension-explained) and the [dictionary guide](/blog/python-dictionary-complete-guide), or learn it all live in our [coding courses](/courses) for learners aged 6 to 67.

[Level Up Your Python](/courses)

### Related reading

- [Python List Comprehension: 15 Examples](/blog/python-list-comprehension-explained)
- [Python Dictionary: The Complete Guide](/blog/python-dictionary-complete-guide)
- [Python OOP Tutorial](/blog/python-oop-tutorial-for-beginners)

---

*Source: https://learn.modernagecoders.com/blog/python-lambda-functions/*
