Python Basics — Lambda Expressions
Lambda Expressions
A lambda is a small anonymous function defined in a single expression. Lambdas are useful when you need a quick throwaway function.
Lambda Syntax
lambda parameters: expression
The lambda automatically returns the result of the expression — no return keyword needed.
# Regular function
def square(x):
return x ** 2
# Equivalent lambda
square = lambda x: x ** 2
print(square(5)) # 25
Lambda vs def Comparison
| Feature | def |
lambda |
|---|---|---|
| Name | Required | Optional (anonymous) |
| Body | Multiple statements | Single expression only |
| Return | Explicit return |
Implicit (returns expression) |
| Readability | Better for complex logic | Better for simple operations |
| Docstrings | Supported | Not supported |
# def — multi-line logic
def classify(n):
if n > 0:
return "positive"
elif n < 0:
return "negative"
else:
return "zero"
# lambda — single expression only
classify = lambda n: "positive" if n > 0 else ("negative" if n < 0 else "zero")
print(classify(5)) # positive
print(classify(-3)) # negative
print(classify(0)) # zero
When to Use Lambda
Lambdas are best used inline — passed directly as arguments to other functions:
# ✅ Good use — inline with sorted()
students = [("Alice", 85), ("Bob", 92), ("Charlie", 78)]
sorted_students = sorted(students, key=lambda s: s[1])
print(sorted_students) # [('Charlie', 78), ('Alice', 85), ('Bob', 92)]
# ✅ Good use — inline with map()
numbers = [1, 2, 3, 4, 5]
doubled = list(map(lambda x: x * 2, numbers))
print(doubled) # [2, 4, 6, 8, 10]
# ❌ Bad use — assigning to a variable (use def instead)
# PEP 8 discourages: multiply = lambda x, y: x * y
# Use: def multiply(x, y): return x * y
Lambda with Multiple Parameters
add = lambda a, b: a + b
print(add(3, 4)) # 7
full_name = lambda first, last: f"{first} {last}"
print(full_name("Ravi", "Kumar")) # Ravi Kumar
# With default parameters
greet = lambda name, greeting="Hello": f"{greeting}, {name}!"
print(greet("Alice")) # Hello, Alice!
print(greet("Bob", "Namaste")) # Namaste, Bob!
Lambda Limitations
Lambdas can only contain a single expression — no statements like =, for, if:, while:, print, etc. (though ternary if/else is an expression and IS allowed):
# ✅ Ternary expression — allowed
check = lambda x: "even" if x % 2 == 0 else "odd"
print(check(4)) # even
# ❌ Multiple statements — NOT allowed
# bad = lambda x: x = x + 1 # SyntaxError
# bad = lambda x: print(x); return x # SyntaxError
IIFE — Immediately Invoked Lambda
You can define and call a lambda in one step:
result = (lambda x, y: x + y)(3, 7)
print(result) # 10
# Useful for quick computations
area = (lambda l, w: l * w)(5, 3)
print(area) # 15
This is rare in practice but appears in some code patterns.
Common Lambda Patterns
# Identity function
identity = lambda x: x
# Always return a constant
always_true = lambda: True
# Accessing object attributes
get_name = lambda obj: obj["name"]
# Chained ternary
grade = lambda score: "A" if score >= 90 else ("B" if score >= 80 else ("C" if score >= 70 else "F"))
print(grade(85)) # B
# Tuple operations
first = lambda pair: pair[0]
second = lambda pair: pair[1]
Summary
- Lambda syntax:
lambda params: expression - Returns the expression result automatically
- Best used inline as arguments to
sorted(),map(),filter() - Single expression only — no multi-line logic
- PEP 8: don’t assign lambdas to variables — use
definstead - Great for short, simple operations; use
deffor anything complex
Next up: map() Function →