Lambda Functions
Lambda functions are small, anonymous functions defined with a single expression.
They're perfect for short operations you need to pass to other functions like
sorted(), map(), or filter(). While powerful, lambdas
have their place - knowing when to use them (and when not to) is key to writing clean Python!
Lambda Function Basics
The syntax is lambda arguments: expression. A lambda can take any number of
arguments but consists of a single expression that's automatically returned. Think of it
as a compact way to define simple functions inline.
Click Run to execute your code
lambda x: x + 1 is equivalent to the
mathematical notation ฮปx.x+1. Don't worry about the theory - just think of lambdas as
"inline functions."
Lambda with Built-in Functions
Lambdas truly shine when used with Python's built-in functions that accept function
arguments: sorted() for custom sorting, map() for transforming
data, and filter() for selecting elements.
Click Run to execute your code
sorted(), max(),
and min() accept a key parameter - a function that extracts the
value to compare. Lambdas are perfect here: sorted(items, key=lambda x: x["price"])
sorts by the "price" field.
Advanced Lambda Patterns
Lambdas can include conditional expressions, be returned from functions to create
specialized functions, and work with reduce() for aggregation. These
patterns unlock functional programming techniques in Python.
Click Run to execute your code
def function. Lambdas also can't have docstrings, making them harder to
document.
Lambda vs def: When to Use Which
While lambdas are convenient, they're not always the best choice. Understanding when to
use lambda versus def is crucial for writing readable, maintainable
code. Often, list comprehensions are clearer than map/filter with lambdas.
Click Run to execute your code
Common Mistakes
1. Assigning lambdas to variables (use def instead)
# Not recommended (PEP 8)
square = lambda x: x ** 2
# Better - use def for named functions
def square(x):
return x ** 2
# Lambdas are best used inline
sorted(items, key=lambda x: x.value) # Good!
2. Complex logic in lambdas
# Bad - too complex, hard to read
process = lambda x: x.strip().lower().replace(' ', '_') if x else 'default'
# Better - use a named function
def process(x):
if not x:
return 'default'
return x.strip().lower().replace(' ', '_')
3. Forgetting that lambda captures variables by reference
# Problem: all functions use the LAST value of i
funcs = []
for i in range(3):
funcs.append(lambda: i)
print([f() for f in funcs]) # [2, 2, 2] - not [0, 1, 2]!
# Fix: capture i as default argument
funcs = []
for i in range(3):
funcs.append(lambda i=i: i) # i=i captures current value
print([f() for f in funcs]) # [0, 1, 2] - correct!
4. Using map/filter with lambda when comprehension is clearer
# Overly functional style
result = list(map(lambda x: x*2, filter(lambda x: x > 0, numbers)))
# More Pythonic - use comprehension
result = [x * 2 for x in numbers if x > 0]
# Even clearer for complex operations
result = [
transform(x)
for x in numbers
if is_valid(x)
]
5. Trying to use statements in lambda
# Wrong - print is a statement effect, not useful here
# And assignments aren't allowed
process = lambda x: print(x) # Works but returns None
process = lambda x: x = x + 1 # SyntaxError!
# Lambda can only have expressions
process = lambda x: x + 1 # Expression returns value
Exercise: Sort and Transform
Task: Use lambda functions to sort and transform data.
Requirements:
- Sort a list of products by price (ascending)
- Use
map()to apply a 10% discount to all prices - Use
filter()to get products under $50
Click Run to execute your code
Show Solution
products = [
{"name": "Laptop", "price": 999},
{"name": "Mouse", "price": 25},
{"name": "Keyboard", "price": 75},
{"name": "Monitor", "price": 300}
]
# Sort by price
sorted_products = sorted(products, key=lambda p: p["price"])
print("Sorted by price:")
for p in sorted_products:
print(f" {p['name']}: ${p['price']}")
# Apply 10% discount
discounted = list(map(lambda p: {**p, "price": p["price"] * 0.9}, products))
print("\nWith 10% discount:")
for p in discounted:
print(f" {p['name']}: ${p['price']:.2f}")
# Filter under $50
cheap = list(filter(lambda p: p["price"] < 50, products))
print(f"\nUnder $50: {[p['name'] for p in cheap]}")
Summary
- Syntax:
lambda arguments: expression - Best use: Short operations passed to
sorted(),map(),filter() - With key:
sorted(items, key=lambda x: x.value) - With map:
map(lambda x: x*2, items) - With filter:
filter(lambda x: x > 0, items) - Conditional:
lambda x: "yes" if x else "no" - Limitation: Single expression only, no statements
- When to use def: Named functions, complex logic, need docstrings
- Often prefer: List comprehensions over map/filter with lambda
What's Next?
Now let's explore Recursion - functions that call themselves! This powerful technique is perfect for problems that have a natural recursive structure, like traversing trees, calculating factorials, or solving puzzles.
Enjoying these tutorials?