Skip to content

Lambda Functions

A lambda is an anonymous, single-expression function. Itโ€™s useful for short, throwaway functions โ€” especially as arguments to map, filter, sorted, etc.

lambda arguments: expression
square = lambda x: x ** 2
print(square(5)) # 25
add = lambda a, b: a + b
print(add(3, 4)) # 7
greet = lambda name: f"Hello, {name}!"
print(greet("Alice")) # Hello, Alice!
people = [("Alice", 30), ("Bob", 25), ("Charlie", 35)]
# Sort by age
sorted_people = sorted(people, key=lambda p: p[1])
# [('Bob', 25), ('Alice', 30), ('Charlie', 35)]
# Sort dicts by value
scores = {"Alice": 90, "Bob": 75, "Charlie": 85}
sorted_scores = sorted(scores.items(), key=lambda x: x[1], reverse=True)
nums = [1, 2, 3, 4, 5]
squares = list(map(lambda x: x ** 2, nums))
# [1, 4, 9, 16, 25]
nums = [1, 2, 3, 4, 5, 6]
evens = list(filter(lambda x: x % 2 == 0, nums))
# [2, 4, 6]
from functools import reduce
nums = [1, 2, 3, 4, 5]
product = reduce(lambda a, b: a * b, nums)
# 120
# Lambda
double = lambda x: x * 2
# Equivalent regular function
def double(x):
return x * 2

Use a regular def when:

  • The logic spans multiple lines
  • You need a docstring
  • You need to reuse it in multiple places
  • Readability matters more than brevity
result = (lambda x, y: x + y)(3, 4)
print(result) # 7
  • Only a single expression โ€” no statements, no if/else blocks (ternary is OK)
  • No return keyword
  • No type annotations
  • Harder to debug (shows as <lambda> in tracebacks)
# Ternary in lambda is fine
classify = lambda x: "even" if x % 2 == 0 else "odd"
print(classify(4)) # even