Key Differences Between Lambda and Def Functions
Python's lambda functions provide a concise way to create small anonymous functions. These are particularly useful for short operations where full function definitions would be unnecessarily verbose.
# Traditional function definition
def increment(num):
return num + 1
# Equivalent lambda function
increment_lambda = lambda num: num + 1
print(increment(5)) # Output: 6
print(increment_lambda(5)) # Output: 6
Primary Differences:
- Syntax: def creates a named function while lambda creates an anonymous function object
- Strucutre: def can contain multiple expressions, lambda is limited to a single expression
- Scope: lambda functions can be immediately invoked (IIFE pattern)
When to Use Each Approach
Use def when:
- The function requires multiple statements
- You need to document the function with docstrings
- The function will be reused multiple times
Use lambda when:
- The operation is simple and fits in one expression
- The function is needed temporarily
- You're passing the function as an argument to another function
# Practical lambda usage with built-in functions
numbers = [1, 2, 3, 4, 5]
# Filter even numbers
filtered = filter(lambda x: x % 2 == 0, numbers)
print(list(filtered)) # Output: [2, 4]
# Square all numbers
squared = map(lambda x: x**2, numbers)
print(list(squared)) # Output: [1, 4, 9, 16, 25]
Common Pitfalls with Lambda
Lambda functions have access to variables from the enclosing scope at execution time, not definition time:
# Problematic implementation
functions = [lambda x: x + i for i in range(3)]
print([f(10) for f in functions]) # Output: [12, 12, 12]
# Correct implementation
functions = [lambda x, i=i: x + i for i in range(3)]
print([f(10) for f in functions]) # Output: [10, 11, 12]
Def Function Features
Traditional functions offer more capabilities:
- Default parameters
- Docstrings
- Multiple return points
- Complex logic
def calculate_stats(values, operation='sum'):
"""
Calculate various statistics on a list of values.
Args:
values: List of numerical values
operation: Type of calculation ('sum', 'avg', 'max')
Returns:
Requested statistical value
"""
if not values:
return None
if operation == 'sum':
return sum(values)
elif operation == 'avg':
return sum(values) / len(values)
elif operation == 'max':
return max(values)
else:
raise ValueError("Invalid operation")
Parameter Passing Behavior
Python uses pass-by-object-reference:
- Immutable objects (numbers, strings) behave like pass-by-value
- Mutable objects (lists, dictionaries) behave like pass-by-reference
def modify_args(num, items):
num += 10
items.append('new')
value = 5
collection = [1, 2, 3]
modify_args(value, collection)
print(value) # Output: 5 (unchanged)
print(collection) # Output: [1, 2, 3, 'new'] (modified)