Programming

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.

Modern Age Coders
Modern Age Coders July 3, 2026
7 min read
Python lambda functions explained with 10 tested examples

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

double = lambda x: x * 2

print(double(5))
print(double(21))
10
42

2. Two arguments, same idea

Lambdas take multiple arguments exactly like def functions.

area = lambda length, width: length * width

print(area(5, 3))
print(area(12, 4))
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.

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

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

print(by_length)
['c', 'go', 'java', 'python', 'javascript']
How the key argument works in Python sorted: the lambda measures each item and the ordering follows those measurements
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.

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

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

print(ranked)
[('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.

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

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

print(ranked)
{'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.

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)
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 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.

prices = [120, 250, 80]

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

print(with_gst)
[142, 295, 94]

8. Filter a list with filter()

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

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

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

print(evens)
[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.

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

print([grade(m) for m in [35, 72, 48, 91]])
['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.

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

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

print(ordered)
[('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
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

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.

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.

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.

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.

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.

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

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 is built around.

Round out this level with list comprehensions and the dictionary guide, or learn it all live in our coding courses for learners aged 6 to 67.

Related reading

Modern Age Coders

About Modern Age Coders

Expert educators passionate about making coding accessible and fun for learners of all ages.

Ask Misti AI
Chat with us