Topic 35 of 58
Lambda Functions
Overview
Lambdas are small, anonymous, one-line functions created using the lambda keyword instead of def. They are structurally restricted to a single expression and implicitly return the result of that expression. You use lambdas when you need a simple, throwaway function for a brief period—typically passing them as arguments to higher-order functions like sort(), map(), or filter() where defining a full def function would clutter the code.
Syntax
python
# Syntax: lambda arguments: expression
multiply = lambda x, y: x * y
print(multiply(3, 4)) # 12
# The actual real-world use case: Sorting complex data
users = [
{"name": "Alice", "age": 28},
{"name": "Bob", "age": 22},
{"name": "Charlie", "age": 35}
]
# Sort the dictionaries based on the "age" key
users.sort(key=lambda user: user["age"])
# Bob will now be first in the listCommon Pitfalls
- Trying to put complex logic or statements inside a lambda. Lambdas cannot contain
whileloops,forloops, variable assignments, or multiple lines. They are strictly limited to one expression. - Assigning lambdas to variables (e.g.,
func = lambda x: x). PEP 8 actively discourages this. If you are assigning a name to it, you should just use a standarddeffunction for better debugging and tracebacks.
Interview Questions
Q:
Can a lambda function take multiple arguments?
A:
Yes, a lambda can take any number of arguments, just like a normal function (e.g., lambda a, b, c: a+b+c), but it is still restricted to a single evaluating expression.
Real-World Example
Sorting a list of tuples by a specific index element.
example
python
stock_prices = [("Apple", 150), ("Google", 2800), ("Tesla", 200)]
# We want to sort by price (index 1), not the alphabetical name (index 0)
stock_prices.sort(key=lambda item: item[1])
print(stock_prices)
# [('Apple', 150), ('Tesla', 200), ('Google', 2800)]Check Your Knowledge
Test your understanding of Lambda Functions with these quick questions.