Lambda Functions
Learn to create and use anonymous lambda functions.
Lambda functions are small anonymous functions defined with the lambda keyword. They are useful for short, throwaway functions and functional programming patterns.
π Concepts & Theory
Lambda functions (also called anonymous functions) are one-line functions defined without the def keyword. They're perfect for short, simple operations.
Basic Lambda Syntax:
lambda parameters: expression
Equivalent Forms:
# Regular function
def add(x, y):
return x + y
# Lambda function
add = lambda x, y: x + y
# Both work the same
print(add(3, 5)) # 8
Key Characteristics:
- Single expression only (no statements)
- Implicit return (no return keyword)
- Can have any number of parameters
- Often used without naming (inline)
1. Sorting with Custom Key:
students = [
{"name": "Alice", "grade": 85},
{"name": "Bob", "grade": 92},
{"name": "Charlie", "grade": 78}
]
# Sort by grade
sorted_students = sorted(students, key=lambda s: s["grade"])
2. Map Function:
numbers = [1, 2, 3, 4, 5]
squared = list(map(lambda x: x2, numbers))
# [1, 4, 9, 16, 25]
3. Filter Function:
numbers = [1, 2, 3, 4, 5, 6]
evens = list(filter(lambda x: x % 2 == 0, numbers))
# [2, 4, 6]
4. Reduce Function:**
from functools import reduce
numbers = [1, 2, 3, 4, 5]
product = reduce(lambda x, y: x * y, numbers)
# 120 (1*2*3*4*5)
Multiple Parameters:
multiply = lambda a, b: a * b
result = multiply(5, 3) # 15
Single Parameter:
square = lambda x: x 2
result = square(4) # 16
No Parameters:
get_greeting = lambda: "Hello, World!"
message = get_greeting()
Lambda with Conditional (Ternary):
is_adult = lambda age: "Adult" if age >= 18 else "Minor"
status = is_adult(20) # "Adult"
When to Use Lambdas:
β
Short, simple operations
β
One-time use in higher-order functions
β
Functional programming patterns
β
Callbacks and event handlers
When NOT to Use Lambdas:
β Complex logic (use def instead)
β Multiple statements needed
β Need docstrings or detailed documentation
β Code reusability is important
Limitations:
Best Practice Comparison:
2 if x > 0 else -1 if x < 0 else 0# β Too Complex for Lambda
calculate = lambda x: x
# β
Use def for Complex Logic
def calculate(x):
if x > 0:
return x ** 2
elif x < 0:
return -1
return 0
π― Your Challenge
Create a lambda function that takes two numbers and returns their product. Assign it to variable multiply.
π Starter Code
# multiply = lambda ...
- Use lambda keyword to start
- Parameters come before the colon
- Expression comes after the colon
- The expression is automatically returned
- For multiplication, use x * y
Solution
multiply = lambda x, y: x * y
Explanation
This lambda function demonstrates anonymous function syntax. The lambda keyword declares an anonymous function, x and y are the parameters (separated by commas), the colon separates parameters from the expression, and x * y is the expression that gets evaluated and returned (implicit return). When you call multiply(3, 4), Python evaluates the expression with x=3 and y=4, returning 12. Lambda functions are concise but limited to single expressionsβno statements or multiple lines allowed. They're perfect for simple operations like this multiplication.
β οΈ Common Mistakes to Avoid
- Forgetting the colon between parameters and expression
- Trying to use multiple statements (only expressions allowed)
- Using return keyword (lambdas have implicit return)
- Forgetting parentheses when calling: multiply vs multiply()
- Making the lambda too complex (use def for complex logic)