Lambda Functions
In Python, a lambda is a single-expression, anonymous function. It behaves exactly like a regular def function but is written
in one line and returns its expression implicitly, no return keyword needed:
lambda <arguments> : <expression># Syntax: lambda arguments: expressionsquare = lambda x: x ** 2add = lambda x, y: x + ygreet = lambda name: f"Hello, {name}!"
print(square(5)) # 25print(add(3, 4)) # 7print(greet("Alice")) # Hello, Alice!Lambda vs def — When to Use Which
Section titled “Lambda vs def — When to Use Which”lambda | def | |
|---|---|---|
| Has a name | ❌ Anonymous | ✅ Named |
| Number of expressions | One only | Unlimited |
| Can include statements | ❌ No | ✅ Yes |
| Reusability | Low — inline use | High — defined once, used anywhere |
| Readability | Good for simple logic | Better for complex logic |
# Syntax: lambda arguments: expressionsquare = lambda x: x ** 2add = lambda x, y: x + ygreet = lambda name: f"Hello, {name}!"
print(square(5)) # 25print(add(3, 4)) # 7print(greet("Alice")) # Hello, Alice!
# Lambdas shine as inline argumentsdata = [("Alice", 30), ("Bob", 25), ("Carol", 35)]
# Sort by agesorted_data = sorted(data, key=lambda person: person[1])print(sorted_data) # [('Bob', 25), ('Alice', 30), ('Carol', 35)]
# Sort by name length, then alphabeticallysorted_data = sorted(data, key=lambda p: (len(p[0]), p[0]))
# With filter, map, reducenums = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]evens = list(filter(lambda x: x % 2 == 0, nums))squared = list(map(lambda x: x ** 2, nums))print(evens) # [2, 4, 6, 8, 10]print(squared) # [1, 4, 9, 16, 25, 36, 49, 64, 81, 100]# Limitation — lambdas are single expressions only# Use def for anything complex# ❌ Hard to readprocess = lambda x: x**2 if x > 0 else -x if x < 0 else 0
# ✅ Much clearer as a named functiondef process(x): if x > 0: return x ** 2 if x < 0: return -x return 0