Lambda Functions
Reviewed & published by Brayan K
Sometimes you need a function for just a moment — a tiny rule that says "sort by this" or "double that" — and writing a full def feels heavy. A lambda is a one-line, throwaway function built exactly for these passing needs.
Part of the free Python course at LearnCodingFast — hands-on lessons with examples you run in your browser, plus practice exercises and a quick quiz.
Their natural home is the key argument of sorted(), max(), and min(), plus quick use with map() and filter().
What You'll Learn in This Lesson
- Lambda syntax and how it maps to a def
- Why lambdas can hold only one expression
- Sorting with key= and lambda
- Finding max/min by a custom rule
- Pairing lambdas with map() and filter()
- When to choose def over lambda
1 Lambda Syntax — Same Idea, Tiny Form
A lambda is a normal function squeezed onto one line. Compare the two — they behave identically:
# A regular function
def double(x):
return x * 2
# The exact same logic as a lambda
double = lambda x: x * 2
print(double(5)) # 10 (both versions)📐 Anatomy of a lambda:
lambda x, y : x + y
^^^^^^ ^^^^ ^^^^^^^
keyword params expression (auto-returned)There's no return keyword — the expression's value is the return value. Lambdas can take zero, one, or many parameters.
add = lambda a, b: a + b
print(add(3, 4)) # 7
greet = lambda name: f"Hi {name}!"
print(greet("Ada")) # Hi Ada!
no_args = lambda: 42
print(no_args()) # 42📏 The One-Expression Rule
A lambda body must be a single expression — something that produces a value. You cannot put statements (if-blocks, loops, assignments) inside one:
# ✅ A conditional EXPRESSION is allowed
classify = lambda n: "even" if n % 2 == 0 else "odd"
print(classify(4)) # even
print(classify(7)) # odd
# ✅ Calling other functions is fine
shout = lambda s: s.strip().upper()
print(shout(" hi ")) # HI
# ❌ These are NOT allowed inside a lambda:
# - an if/else BLOCK (statement)
# - a for-loop
# - x = 5 (assignment)
# If you need those, write a def instead.The trick is the conditional expression (a if cond else b) — it looks like a mini if/else but evaluates to a single value, so it's perfectly legal in a lambda.
2 The Killer Use: Sorting with key=
This is where lambdas earn their keep. The key argument of sorted() takes a function that decides what to sort by:
words = ["banana", "kiwi", "apple", "fig"]
# Sort by length instead of alphabetically
print(sorted(words, key=lambda w: len(w)))
# ['fig', 'kiwi', 'apple', 'banana']
# Sort a list of tuples by the SECOND item (the score)
players = [("Ada", 88), ("Ben", 72), ("Cleo", 95)]
print(sorted(players, key=lambda p: p[1]))
# [('Ben', 72), ('Ada', 88), ('Cleo', 95)]
# Highest score first with reverse=True
print(sorted(players, key=lambda p: p[1], reverse=True))
# [('Cleo', 95), ('Ada', 88), ('Ben', 72)]
# Sort names case-insensitively
names = ["bob", "Alice", "charlie", "Dave"]
print(sorted(names, key=lambda n: n.lower()))
# ['Alice', 'bob', 'charlie', 'Dave']The lambda is applied to each element to produce a sort value, but the original elements are what get returned — just reordered. This single pattern accounts for the vast majority of lambdas you'll write.
# Sort a leaderboard several different ways
scores = [
("Maya", 1500, "gold"),
("Omar", 2300, "diamond"),
("Tess", 1500, "gold"),
("Kai", 900, "silver"),
]
# By score, highest first
by_score = sorted(scores, key=lambda p: p[1], reverse=True)
print("Top players:")
for name, pts, rank in by_score:
print(f" {name:<6} {pts:>5} ({rank})")
# By name alphabetically
by_name = sorted(scores, key=lambda p: p[0])
print("Alphabetical:", [p[0] for p in by_name])
# ✅ Expected output:
# Top players:
# Omar 2300 (diamond)
# Maya 1500 (gold)
# Tess 1500 (gold)
# Kai 900 (silver)
# Alphabetical: ['Kai', 'Maya', 'Omar', 'Tess']3 max() and min() Take key= Too
The same key idea works with max() and min() to find the "biggest" or "smallest" by any rule you like:
products = [
{"name": "Mouse", "price": 25},
{"name": "Monitor", "price": 180},
{"name": "Cable", "price": 8},
]
# Most expensive product
priciest = max(products, key=lambda p: p["price"])
print(priciest["name"]) # Monitor
# Cheapest product
cheapest = min(products, key=lambda p: p["price"])
print(cheapest["name"]) # Cable
# Longest word in a sentence
sentence = "the quick brown fox"
print(max(sentence.split(), key=len)) # quick🔧 Lambdas with map() and filter()
map() applies a function to every item; filter() keeps items where the function returns True. Lambdas supply that function inline:
nums = [1, 2, 3, 4, 5, 6]
# map: transform every item
doubled = list(map(lambda n: n * 2, nums))
print(doubled) # [2, 4, 6, 8, 10, 12]
# filter: keep only matching items
evens = list(filter(lambda n: n % 2 == 0, nums))
print(evens) # [2, 4, 6]🧩 Reorder Challenge
These lines should find the longest word in a list and print it. Reorder them so the output is Longest: elephant.
A) longest = max(words, key=lambda w: len(w))
B) words = ["cat", "elephant", "dog", "fox"]
C) print(f"Longest: {longest}")words = ["cat", "elephant", "dog", "fox"] # B
longest = max(words, key=lambda w: len(w)) # A -> "elephant"
print(f"Longest: {longest}") # CWhy: the words list (B) must exist before max (A) can scan it. The lambda len(w) tells max to compare by length, so it returns elephant (8 letters). The print (C) comes last.
🧠 Quick Recall
f = lambda x: x + 10
print(f(5))15 — the lambda takes x and returns x + 10; calling it with 5 gives 15.
2. What is the result?
pairs = [(1, "b"), (2, "a")]
print(sorted(pairs, key=lambda p: p[1]))[(2, 'a'), (1, 'b')] — sorting by p[1] orders by the letters, so "a" comes before "b".
3. What does this log?
print(list(filter(lambda n: n > 2, [1, 2, 3, 4])))[3, 4] — filter keeps only items where the lambda returns True, i.e. numbers greater than 2.
📋 Lambda Quick Reference
| Use | Example | Result |
|---|---|---|
| Basic | (lambda x: x*x)(4) | 16 |
| Sort by field | sorted(t, key=lambda x: x[1]) | by 2nd item |
| Max by rule | max(p, key=lambda x: x["n"]) | biggest by n |
| Conditional | lambda n: "+" if n>0 else "-" | sign label |
| filter | filter(lambda n: n%2, nums) | odds only |
🎯 Mini Challenge: Sort Files by Size
Given a list of (filename, size_kb) tuples, sort and summarize them with lambdas.
# 🎯 YOUR TURN: file manager logic
files = [
("report.pdf", 240),
("photo.jpg", 1800),
("notes.txt", 12),
("video.mp4", 52000),
]
# Sort smallest to largest
by_size = sorted(files, key=lambda f: f[1])
for name, size in by_size:
print(f"{name:<12} {size:>6} KB")
# Biggest file
biggest = max(files, key=lambda f: f[1])
print("Largest:", biggest[0])
# Only files under 1 MB (1000 KB)
small = list(filter(lambda f: f[1] < 1000, files))
print("Small files:", [f[0] for f in small])
# ✅ Expected output:
# notes.txt 12 KB
# report.pdf 240 KB
# photo.jpg 1800 KB
# video.mp4 52000 KB
# Largest: video.mp4
# Small files: ['report.pdf', 'notes.txt']Lesson complete — lambdas demystified!
You can write one-line lambdas, understand the single-expression rule, and use them where they truly shine: the key argument of sorted(), max(), and min(). And you know when a plain def is the better choice.
Practice quiz
What is a lambda?
- A class definition
- A type of loop
- A small anonymous function in a single expression
- A module
Answer: A small anonymous function in a single expression. A lambda is a tiny anonymous function defined in one expression, e.g. lambda x: x * 2.
Which def is equivalent to: double = lambda x: x * 2?
- def double(x): return x * 2
- def double(x): print(x * 2)
- def double(): return x * 2
- def double(x): x * 2
Answer: def double(x): return x * 2. A lambda auto-returns its expression, so it matches def double(x): return x * 2.
Does a lambda use the return keyword?
- Yes, it requires return
- Only with multiple arguments
- Only inside sorted()
- No, the expression's value is returned automatically
Answer: No, the expression's value is returned automatically. There is no return keyword; the single expression's value IS the return value.
What must a lambda body be?
- A block of statements
- A single expression
- A for-loop
- An assignment
Answer: A single expression. A lambda body must be one expression — no if-blocks, loops, or assignments allowed.
Which is legal inside a lambda?
- A conditional expression: a if cond else b
- An if/else block
- A for-loop
- x = 5
Answer: A conditional expression: a if cond else b. A conditional expression (a if cond else b) evaluates to a value, so it's allowed.
What does sorted(words, key=lambda w: len(w)) do?
- Sorts alphabetically
- Reverses the list
- Sorts by word length
- Removes duplicates
Answer: Sorts by word length. The key applies len to each word, so the list is sorted by length.
What does sorted([(1,'b'),(2,'a')], key=lambda p: p[1]) return?
- [(1,'b'),(2,'a')]
- [(2,'a'),(1,'b')]
- [(1,'a'),(2,'b')]
- [('a',2),('b',1)]
Answer: [(2,'a'),(1,'b')]. Sorting by p[1] orders by the letters, so 'a' comes before 'b': [(2,'a'),(1,'b')].
What does list(filter(lambda n: n > 2, [1,2,3,4])) return?
- [1, 2]
- [1, 2, 3, 4]
- [2, 3, 4]
- [3, 4]
Answer: [3, 4]. filter keeps items where the lambda is True, i.e. numbers greater than 2: [3, 4].
What does list(map(lambda n: n * 2, [1, 2, 3])) return?
- [1, 2, 3]
- [2, 4, 6]
- [1, 4, 9]
- [3, 6, 9]
Answer: [2, 4, 6]. map applies the lambda to each item, doubling them: [2, 4, 6].
Per PEP 8, what is preferred when you want to NAME a function?
- Assign a lambda to a variable
- Use map()
- Use a def instead of a named lambda
- Use a class
Answer: Use a def instead of a named lambda. Style guides recommend def over assigning a lambda to a name — it's clearer in tracebacks.
Continue this course
- Previous: *args & **kwargs
- Next: f-strings & String Formatting — Format strings cleanly with f-strings — the modern Python standard
- Quick reference: Python cheat sheet › Useful Builtins
Frequently asked questions
What is a lambda function?
A lambda is a small anonymous function defined in a single expression: lambda x: x * 2. It has no name (unless you assign it to a variable), can take any number of arguments, and automatically returns the value of its single expression — there's no return keyword and no body block.
When should I use a lambda instead of def?
Use a lambda for a short, throwaway function you pass to another function — most often the key argument of sorted(), max(), or min(), or a quick transform for map() and filter(). If the logic needs more than one expression, a name for clarity, or reuse in several places, write a normal def function instead.
Why can't a lambda contain statements like if-blocks or loops?
A lambda body must be a single expression, not a series of statements. You can use a conditional expression (a if cond else b) because that's an expression, but you cannot use an if-block, a for-loop, or an assignment. That deliberate restriction keeps lambdas tiny; anything bigger belongs in a def.
What does the key argument in sorted() actually do?
key takes a function that's applied to each element to decide what to sort by, without changing the elements themselves. sorted(words, key=len) sorts by length; sorted(people, key=lambda p: p[1]) sorts a list of tuples by their second item. The original values are returned, just reordered.
Is it bad style to assign a lambda to a variable?
Generally yes. If you're giving a lambda a name, you usually want a def instead — it's clearer, shows the name in tracebacks, and reads better. The idiomatic use of lambda is inline and unnamed, passed directly as an argument. Style guides like PEP 8 specifically recommend def over a named lambda.