A lambda is a small, anonymous, single-line function.
# Regular function
def double(x):
return x * 2
# Lambda
double = lambda x: x * 2
double(5) # 10
Syntax
lambda arguments: expression
lambda— keywordarguments— parameters (same as indef)expression— the result (one line, returned automatically)
Examples
# Arithmetic
add = lambda a, b: a + b
print(add(3, 5)) # 8
square = lambda x: x ** 2
print(square(4)) # 16
is_even = lambda n: n % 2 == 0
print(is_even(10)) # True
# Strings
greet = lambda name: f"Hello, {name}!"
print(greet("Alice")) # Hello, Alice!
# Conditional
max_num = lambda a, b: a if a > b else b
print(max_num(10, 20)) # 20
When to Use
Lambda is convenient inside other functions — as a key= argument or instead of short helper functions.
numbers = [5, 2, 8, 1, 9]
sorted_desc = sorted(numbers, key=lambda x: -x)
print(sorted_desc) # [9, 8, 5, 2, 1]
doubled = list(map(lambda x: x * 2, numbers))
print(doubled) # [10, 4, 16, 2, 18]
even = list(filter(lambda x: x % 2 == 0, numbers))
print(even) # [2, 8]
When NOT to Use
Complex logic — readability suffers:
# Bad
check = lambda x: x > 0 and x < 100 and x % 2 == 0 and str(x)[0] != "5"
# Good — use a regular function
def check_number(x):
if x <= 0 or x >= 100:
return False
if x % 2 != 0:
return False
return str(x)[0] != "5"
Documentation needed — lambda doesn’t support docstrings.
Lambda vs def
| Lambda | def | |
|---|---|---|
| Length | One line | Any length |
| Name | Anonymous | Required |
| Docstring | ❌ | ✅ |
| Complexity | Simple expressions only | Anything |
Practical Examples
products = [
{"name": "Laptop", "price": 50000},
{"name": "Mouse", "price": 500},
{"name": "Keyboard", "price": 3000}
]
# Sort by price
cheap_first = sorted(products, key=lambda p: p["price"])
print(cheap_first[0]["name"]) # Mouse
# Find the most expensive
most_expensive = max(products, key=lambda p: p["price"])
print(most_expensive["name"]) # Laptop
# Words by length
words = ["Python", "Go", "JavaScript", "Rust"]
by_length = sorted(words, key=lambda w: len(w))
print(by_length) # ['Go', 'Rust', 'Python', 'JavaScript']
Common Mistakes
Mistake 1: Multiple lines — not allowed
# Error — lambda is only one line
calc = lambda x:
result = x * 2 # SyntaxError
return result
# Correct
calc = lambda x: x * 2
Mistake 2: Assignment inside a lambda
update = lambda x: x = x + 1 # SyntaxError
# Use def for this
Mistake 3: Saving a lambda to a variable
# Bad — if you're saving it, use def instead
double = lambda x: x * 2
square = lambda x: x ** 2
# Good
def double(x):
return x * 2
def square(x):
return x ** 2
Lambda is for one-time use inside another function. If you’re saving it to a variable — use def.
💬 Comments (0)
No comments yet
Be the first to share your opinion about this article!