
Python
Lambda functions are one-line, unnamed functions perfect for simple operations.
A lambda function is a small anonymous function defined with the `lambda` keyword:
# Regular function
def square(x):
return x ** 2
# Equivalent lambda function
square = lambda x: x ** 2
print(square(5)) # 25lambda parameters: expressionComponents:
# Regular function
def add_ten(x):
return x + 10
# Lambda equivalent
add_ten = lambda x: x + 10
print(add_ten(5)) # 15
print(add_ten(20)) # 30# Regular function
def add(a, b):
return a + b
# Lambda equivalent
add = lambda a, b: a + b
print(add(5, 3)) # 8
print(add(10, 20)) # 30# Check if even
is_even = lambda x: x % 2 == 0
print(is_even(4)) # True
print(is_even(7)) # False
# Return different values
grade = lambda score: "A" if score >= 90 else "B" if score >= 80 else "C"
print(grade(95)) # A
print(grade(85)) # B
print(grade(75)) # CTransform each element in a list:
numbers = [1, 2, 3, 4, 5]
# Square each number
squared = list(map(lambda x: x ** 2, numbers))
print(squared) # [1, 4, 9, 16, 25]
# Convert to strings
strings = list(map(lambda x: str(x), numbers))
print(strings) # ['1', '2', '3', '4', '5']
# Double each number
doubled = list(map(lambda x: x * 2, numbers))
print(doubled) # [2, 4, 6, 8, 10]Keep only elements that match a condition:
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
# Filter even numbers
evens = list(filter(lambda x: x % 2 == 0, numbers))
print(evens) # [2, 4, 6, 8, 10]
# Filter numbers > 5
greater_than_five = list(filter(lambda x: x > 5, numbers))
print(greater_than_five) # [6, 7, 8, 9, 10]
# Filter non-empty strings
words = ["hello", "", "world", "", "python"]
non_empty = list(filter(lambda w: w != "", words))
print(non_empty) # ['hello', 'world', 'python']Combine all elements into a single result:
from functools import reduce
numbers = [1, 2, 3, 4, 5]
# Calculate product (multiply all)
product = reduce(lambda x, y: x * y, numbers)
print(product) # 120
# Calculate sum
total = reduce(lambda x, y: x + y, numbers)
print(total) # 15
# Find maximum
maximum = reduce(lambda x, y: x if x > y else y, numbers)
print(maximum) # 5data = [
{"name": "Alice", "score": 85},
{"name": "Bob", "score": 92},
{"name": "Charlie", "score": 78},
]
# Extract just the scores
scores = list(map(lambda d: d["score"], data))
print(scores) # [85, 92, 78]
# Filter passing grades (>= 80)
passing = list(filter(lambda d: d["score"] >= 80, data))
print(passing)
# [{'name': 'Alice', 'score': 85}, {'name': 'Bob', 'score': 92}]students = [
("Alice", 85),
("Bob", 92),
("Charlie", 78),
]
# Sort by score
sorted_students = sorted(students, key=lambda x: x[1])
print(sorted_students)
# [('Charlie', 78), ('Alice', 85), ('Bob', 92)]
# Sort by name
sorted_by_name = sorted(students, key=lambda x: x[0])
print(sorted_by_name)
# [('Alice', 85), ('Bob', 92), ('Charlie', 78)]Lambda functions can only contain one expression:
# ✅ Works - single expression
square = lambda x: x ** 2
# ❌ Doesn't work - multiple statements
divide = lambda x, y: (
if y == 0:
return "Error"
else:
return x / y
)
# ✅ Use regular function instead
def divide(x, y):
if y == 0:
return "Error"
return x / y# Good - used once with map
squared = list(map(lambda x: x ** 2, [1, 2, 3]))
# Good - sorting key
sorted_data = sorted(data, key=lambda x: x["age"])# Bad - should be regular function
process = lambda data: (
validate(data),
transform(data),
save(data)
)
# Better - use regular function
def process(data):
validated = validate(data)
transformed = transform(data)
save(transformed)
return transformed# For simple cases, lambda is cleaner
numbers = [1, 2, 3, 4, 5]
# With lambda - concise
doubled_lambda = list(map(lambda x: x * 2, numbers))
# With regular function - verbose
def double(x):
return x * 2
doubled_func = list(map(double, numbers))
# Both produce: [2, 4, 6, 8, 10]| Concept | Remember |
|---|---|
| Lambda | One-line anonymous function |
| Syntax | `lambda params: expression` |
| map() | Transform each element |
| filter() | Keep elements matching condition |
| reduce() | Combine all elements |
| When | Use for simple, one-off functions |
| Avoid | Complex logic, multiple statements |
Now that you know lambda functions, explore decorators to enhance function behavior with elegant patterns.
Practice: Lambda challenges
Resources
Ojasa Mirai
Master AI-powered development skills through structured learning, real projects, and verified credentials. Whether you're upskilling your team or launching your career, we deliver the skills companies actually need.
Learn Deep • Build Real • Verify Skills • Launch Forward