lambda
Updated March 16, 2026 · Keywords
keyword function anonymous functional
The lambda keyword creates anonymous functions in Python. Lambda functions are small, single-expression functions that don’t need a name. They’re useful when you need a short function for a brief operation, especially as arguments to higher-order functions like map(), filter(), and sorted().
Syntax
lambda parameters: expression
Unlike regular functions, lambda functions can only contain a single expression — no statements, no multiple lines, no docstrings.
Basic Examples
Simple Lambda
# Lambda that doubles a number
double = lambda x: x * 2
print(double(5))
# 10
Lambda with Multiple Parameters
# Lambda with two parameters
add = lambda a, b: a + b
print(add(3, 4))
# 7
Lambda without Parameters
# Lambda that always returns 42
answer = lambda: 42
print(answer())
# 42
Common Use Cases
Sorting with key
Lambda shines when you need a custom sort key:
words = ["apple", "banana", "cherry", "date"]
# Sort by length
sorted_by_length = sorted(words, key=lambda w: len(w))
print(sorted_by_length)
# ['date', 'apple', 'banana', 'cherry']
# Sort by last character
sorted_by_last = sorted(words, key=lambda w: w[-1])
print(sorted_by_last)
# ['banana', 'apple', 'date', 'cherry']
Sorting Complex Data
people = [
{"name": "Alice", "age": 30},
{"name": "Bob", "age": 25},
{"name": "Charlie", "age": 35}
]
# Sort by age
sorted_by_age = sorted(people, key=lambda p: p["age"])
print([p["name"] for p in sorted_by_age])
# ['Bob', 'Alice', 'Charlie']
# Sort by name length
sorted_by_name_len = sorted(people, key=lambda p: len(p["name"]))
print([p["name"] for p in sorted_by_name_len])
# ['Bob', 'Alice', 'Charlie']
map() with Lambda
Apply a function to every element:
numbers = [1, 2, 3, 4, 5]
# Double each number
doubled = list(map(lambda x: x * 2, numbers))
print(doubled)
# [2, 4, 6, 8, 10]
# Convert to strings
as_strings = list(map(lambda x: str(x), numbers))
print(as_strings)
# ['1', '2', '3', '4', '5']
filter() with Lambda
Select elements that match a condition:
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
# Keep only even numbers
evens = list(filter(lambda x: x % 2 == 0, numbers))
print(evens)
# [2, 4, 6, 8, 10]
# Keep numbers greater than 5
greater_than_5 = list(filter(lambda x: x > 5, numbers))
print(greater_than_5)
# [6, 7, 8, 9, 10]
Chaining map and filter
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
# Double even numbers
result = list(map(lambda x: x * 2, filter(lambda x: x % 2 == 0, numbers)))
print(result)
# [4, 8, 12, 16, 20]
max() and min() with key
students = [
{"name": "Alice", "score": 85},
{"name": "Bob", "score": 92},
{"name": "Charlie", "score": 78}
]
top_student = max(students, key=lambda s: s["score"])
print(top_student)
# {'name': 'Bob', 'score': 92}
lowest_student = min(students, key=lambda s: s["score"])
print(lowest_student)
# {'name': 'Charlie', 'score': 78}
defaultdict with Lambda
from collections import defaultdict
# Lambda as factory function
point = lambda: (0, 0)
positions = defaultdict(point)
positions["player1"]
positions["player2"]
print(dict(positions))
# {'player1': (0, 0), 'player2': (0, 0)}
Conditional Expressions in Lambda
# Lambda with conditional
absolute = lambda x: x if x >= 0 else -x
print(absolute(-5))
# 5
print(absolute(3))
# 3
Lambda vs Regular Functions
| Feature | Lambda | Regular Function |
|---|---|---|
| Name | Anonymous | Has a name |
| Statements | Not allowed | Allowed |
| Docstrings | Not allowed | Allowed |
| Multiple expressions | Not allowed | Allowed |
| Return | Implicit | Explicit or implicit |
# Lambda
square = lambda x: x ** 2
# Equivalent regular function
def square(x):
return x ** 2
When to Use Lambda
Lambda is appropriate when:
- The function is short (one line)
- The function is used immediately (passed as argument)
- You don’t need to reuse the function elsewhere
Use a regular def function when:
- The function is complex or long
- You need docstrings
- You need multiple statements
- The function will be reused in multiple places
Common Mistakes
Forgetting that lambda is an expression
# This works
f = lambda x: x * 2
# This doesn't work - lambda needs to be an expression
if lambda x: x > 0: # SyntaxError!
pass
Trying to use statements
# This doesn't work
f = lambda x: if x > 0: x else -x # SyntaxError!
# Use conditional expression instead
f = lambda x: x if x > 0 else -x
See Also
- def-keyword — defining regular functions
- sorted built-in — sorting with custom keys
- map built-in — applying functions to iterables
- filter built-in — filtering iterables