A lambda is a tiny anonymous function written as one expression.
Use lambda when a short transformation is needed directly inside sorted(), map(), filter(), or another function call.
If the logic needs a name, multiple lines, error handling, or explanation, a normal def function is clearer.
A lambda is a small, anonymous (unnamed) function defined in a single line. It can take any number of arguments but can only have one expression. The result of the expression is automatically returned.
Syntax: lambda arguments: expression
# Regular function
def square(x):
return x ** 2
# Equivalent lambda
square = lambda x: x ** 2
print(square(5)) # 25
# Lambda with multiple arguments
add = lambda a, b: a + b
print(add(3, 7)) # 10
multiply = lambda a, b, c: a * b * c
print(multiply(2, 3, 4)) # 24
# Lambda with condition
is_even = lambda n: n % 2 == 0
print(is_even(4)) # True
print(is_even(7)) # False
# Immediately invoked lambda
result = (lambda x, y: x + y)(10, 20)
print(result) # 30
The most common use of lambda is as a key function for sorting.
# Sort by string length
words = ["banana", "apple", "cherry", "fig", "date"]
sorted_words = sorted(words, key=lambda w: len(w))
print(sorted_words) # ['fig', 'date', 'apple', 'banana', 'cherry']
# Sort list of dicts by a field
students = [
{"name": "Alice", "grade": 92},
{"name": "Bob", "grade": 85},
{"name": "Charlie", "grade": 97},
]
by_grade = sorted(students, key=lambda s: s["grade"], reverse=True)
for s in by_grade:
print(f"{s['name']}: {s['grade']}")
# Charlie: 97
# Alice: 92
# Bob: 85
# Sort tuples by second element
pairs = [(1, 3), (2, 1), (3, 2)]
pairs.sort(key=lambda p: p[1])
print(pairs) # [(2, 1), (3, 2), (1, 3)]
numbers = [1, 2, 3, 4, 5, 6, 7, 8]
# map() - apply function to every item
squares = list(map(lambda x: x**2, numbers))
print(squares) # [1, 4, 9, 16, 25, 36, 49, 64]
# filter() - keep items where function returns True
evens = list(filter(lambda x: x % 2 == 0, numbers))
print(evens) # [2, 4, 6, 8]
# reduce() - accumulate to a single value
from functools import reduce
product = reduce(lambda acc, x: acc * x, numbers)
print(product) # 40320 (8!)
total = reduce(lambda acc, x: acc + x, numbers)
print(total) # 36
# Note: list comprehensions are often preferred over map/filter
squares_comp = [x**2 for x in numbers]
evens_comp = [x for x in numbers if x % 2 == 0]
| Feature | Lambda | def Function |
|---|---|---|
| Name | Anonymous | Named |
| Lines | Single line | Multiple lines |
| Statements | Expression only | Any statements |
| Docstring | No | Yes |
| Best for | Short, throwaway functions | Reusable, complex logic |
# Good use: short key function inline
data = [{"x": 3}, {"x": 1}, {"x": 2}]
data.sort(key=lambda d: d["x"])
# Good use: simple callback
buttons = ["OK", "Cancel", "Help"]
actions = {btn: lambda b=btn: print(f"Clicked: {b}") for btn in buttons}
actions["OK"]() # Clicked: OK
# Bad use: complex logic (use def instead)
# Avoid this:
process = lambda x: x**2 if x > 0 else -x if x < 0 else 0
# Better as a named function:
def process(x):
if x > 0:
return x ** 2
elif x < 0:
return -x
return 0
0 of 2 checked
Try this next
0 of 3 completed
No. A lambda contains one expression. Use def when the logic needs multiple lines or clear explanation.
No meaningful beginner difference. Choose lambda for small inline expressions and def for named reusable logic.
They often appear in sorted(key=...), map(), filter(), and callback-style code where a tiny function is needed once.
Explore 500+ free tutorials across 20+ languages and frameworks.