Lambda Functions: Anonymous Functions for Quick Tasks
Welcome to lambda functions! These are like disposable cameras - simple, one-purpose tools that you use and discard. Perfect for quick, simple operations!
What are Lambda Functions?
Lambda functions are anonymous functions - they don’t have names. They’re perfect for:
- Simple operations
- One-time use functions
- Functions as arguments to other functions
Think of them as function recipes that you can write quickly without the full function definition.
Basic Lambda Syntax
Regular Function vs Lambda
# Regular function
def square(x):
return x ** 2
# Lambda equivalent
square_lambda = lambda x: x ** 2
# Both do the same thing
print(square(5)) # 25
print(square_lambda(5)) # 25
Real-Life Example: Quick Calculations
# Different calculations as lambdas
add = lambda x, y: x + y
subtract = lambda x, y: x - y
multiply = lambda x, y: x * y
divide = lambda x, y: x / y if y != 0 else "Cannot divide by zero"
print(add(10, 5)) # 15
print(subtract(10, 5)) # 5
print(multiply(10, 5)) # 50
print(divide(10, 5)) # 2.0
print(divide(10, 0)) # "Cannot divide by zero"
Lambda with Built-in Functions
map() - Transform Each Item
# Regular way
def square(x):
return x ** 2
numbers = [1, 2, 3, 4, 5]
squared_regular = list(map(square, numbers))
print(squared_regular) # [1, 4, 9, 16, 25]
# Lambda way
squared_lambda = list(map(lambda x: x ** 2, numbers))
print(squared_lambda) # [1, 4, 9, 16, 25]
filter() - Keep Items That Match
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
# Regular way
def is_even(x):
return x % 2 == 0
even_regular = list(filter(is_even, numbers))
print(even_regular) # [2, 4, 6, 8, 10]
# Lambda way
even_lambda = list(filter(lambda x: x % 2 == 0, numbers))
print(even_lambda) # [2, 4, 6, 8, 10]
sorted() with Custom Key
students = [
("Alice", 85),
("Bob", 92),
("Charlie", 78),
("Diana", 96)
]
# Sort by grade (second element in tuple)
sorted_by_grade = sorted(students, key=lambda student: student[1])
print(sorted_by_grade)
# [('Charlie', 78), ('Alice', 85), ('Bob', 92), ('Diana', 96)]
# Sort by name length
sorted_by_name_length = sorted(students, key=lambda student: len(student[0]))
print(sorted_by_name_length)
# [('Bob', 92), ('Alice', 85), ('Diana', 96), ('Charlie', 78)]
Real-World Examples
Example 1: Data Processing
# Sample data
products = [
{"name": "Laptop", "price": 999, "category": "Electronics"},
{"name": "Book", "price": 20, "category": "Education"},
{"name": "Headphones", "price": 149, "category": "Electronics"},
{"name": "Coffee Mug", "price": 12, "category": "Kitchen"}
]
# Filter expensive products (> $100)
expensive_products = list(filter(lambda p: p["price"] > 100, products))
print("Expensive products:")
for product in expensive_products:
print(f" {product['name']}: ${product['price']}")
# Get product names only
product_names = list(map(lambda p: p["name"], products))
print(f"\nProduct names: {product_names}")
# Calculate total value
total_value = sum(map(lambda p: p["price"], products))
print(f"Total inventory value: ${total_value}")
# Group by category
electronics = list(filter(lambda p: p["category"] == "Electronics", products))
print(f"\nElectronics: {len(electronics)} items")
Example 2: Text Processing
sentences = [
"The quick brown fox jumps over the lazy dog",
"Python is a powerful programming language",
"Lambda functions are anonymous",
"Data science requires analytical thinking"
]
# Get sentence lengths
sentence_lengths = list(map(lambda s: len(s), sentences))
print(f"Sentence lengths: {sentence_lengths}")
# Filter long sentences (> 40 characters)
long_sentences = list(filter(lambda s: len(s) > 40, sentences))
print(f"\nLong sentences: {long_sentences}")
# Count words in each sentence
word_counts = list(map(lambda s: len(s.split()), sentences))
print(f"Word counts: {word_counts}")
# Find sentences containing "Python"
python_sentences = list(filter(lambda s: "Python" in s, sentences))
print(f"\nSentences with 'Python': {python_sentences}")
Example 3: Mathematical Operations
import math
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
# Calculate squares
squares = list(map(lambda x: x ** 2, numbers))
print(f"Squares: {squares}")
# Calculate square roots
square_roots = list(map(lambda x: round(math.sqrt(x), 2), numbers))
print(f"Square roots: {square_roots}")
# Check if numbers are perfect squares
def is_perfect_square(n):
root = int(math.sqrt(n))
return root * root == n
perfect_squares = list(filter(lambda x: is_perfect_square(x), numbers))
print(f"Perfect squares: {perfect_squares}")
# Calculate factorial (for small numbers)
factorials = list(map(lambda x: math.factorial(x), range(1, 6)))
print(f"Factorials 1-5: {factorials}")
Lambda in Conditional Expressions
Simple Conditions
numbers = [-5, -2, 0, 3, 7, -1, 4]
# Get absolute values
abs_values = list(map(lambda x: x if x >= 0 else -x, numbers))
print(f"Absolute values: {abs_values}")
# Classify numbers
classifications = list(map(
lambda x: "positive" if x > 0 else "negative" if x < 0 else "zero",
numbers
))
print(f"Classifications: {classifications}")
Complex Conditions
students = [
{"name": "Alice", "grade": 85, "attendance": 95},
{"name": "Bob", "grade": 92, "attendance": 88},
{"name": "Charlie", "grade": 78, "attendance": 97},
{"name": "Diana", "grade": 96, "attendance": 82}
]
# Determine if student passes (grade >= 80 AND attendance >= 90)
pass_fail = list(map(
lambda s: "Pass" if s["grade"] >= 80 and s["attendance"] >= 90 else "Fail",
students
))
for student, result in zip(students, pass_fail):
print(f"{student['name']}: {result}")
Lambda with Multiple Parameters
Basic Multiple Parameters
# Calculate weighted average
weighted_avg = lambda score, weight: score * weight
# Test scores with weights
scores = [85, 92, 78]
weights = [0.3, 0.4, 0.3] # 30%, 40%, 30%
# Calculate weighted scores
weighted_scores = list(map(weighted_avg, scores, weights))
total_weighted = sum(weighted_scores)
print(f"Weighted average: {total_weighted:.1f}")
Complex Calculations
# Calculate BMI
calculate_bmi = lambda weight_kg, height_m: weight_kg / (height_m ** 2)
# Classify BMI
classify_bmi = lambda bmi: (
"Underweight" if bmi < 18.5
else "Normal" if bmi < 25
else "Overweight" if bmi < 30
else "Obese"
)
# Sample data
people = [
("Alice", 65, 1.70),
("Bob", 80, 1.75),
("Charlie", 90, 1.80)
]
print("BMI Calculations:")
for name, weight, height in people:
bmi = calculate_bmi(weight, height)
category = classify_bmi(bmi)
print(f"{name}: BMI = {bmi:.1f} ({category})")
Advanced Lambda Patterns
Lambda with Default Values
# Lambda with default parameters
power = lambda x, n=2: x ** n
print(power(5)) # 25 (default n=2)
print(power(5, 3)) # 125 (n=3)
print(power(2, 10)) # 1024 (2^10)
Immediately Invoked Lambda
# IIFE (Immediately Invoked Function Expression)
result = (lambda x, y: x + y)(10, 20)
print(result) # 30
# More complex example
message = (lambda name, age: f"Hello {name}, you are {age} years old!")("Alice", 25)
print(message)
Lambda Returning Lambda
# Function that returns a lambda
def make_multiplier(factor):
return lambda x: x * factor
# Create specific multipliers
double = make_multiplier(2)
triple = make_multiplier(3)
quadruple = make_multiplier(4)
print(double(5)) # 10
print(triple(5)) # 15
print(quadruple(5)) # 20
When to Use Lambda vs Regular Functions
Use Lambda When:
# ✅ Short, simple operations
numbers = [1, 2, 3, 4, 5]
squares = list(map(lambda x: x ** 2, numbers))
# ✅ One-time use functions
sorted_list = sorted(data, key=lambda x: x["price"])
# ✅ Functions as arguments
button.on_click(lambda: print("Button clicked!"))
Use Regular Functions When:
# ✅ Complex logic
def calculate_tax(income, brackets):
# Complex tax calculation logic
pass
# ✅ Multiple statements
def process_user_data(user):
validate_user(user)
save_to_database(user)
send_welcome_email(user)
log_activity(user)
# ✅ Need docstrings and documentation
def fibonacci(n):
"""Calculate the nth Fibonacci number."""
if n <= 1:
return n
return fibonacci(n-1) + fibonacci(n-2)
# ✅ Recursive functions
def factorial(n):
if n <= 1:
return 1
return n * factorial(n-1)
Common Lambda Mistakes
1. Trying to Use Statements
# ❌ Wrong - lambda can't have statements
# lambda x: print(x); return x # SyntaxError
# ✅ Correct - lambda can only have expressions
lambda x: x ** 2 # Expression
2. Forgetting Return
# ❌ Wrong - lambda automatically returns the expression
# lambda x: return x ** 2 # SyntaxError
# ✅ Correct - no explicit return needed
lambda x: x ** 2
3. Complex Lambdas
# ❌ Too complex - hard to read
complex_lambda = lambda x: x if x > 0 else -x if x < 0 else 0
# ✅ Better as a regular function
def normalize_number(x):
if x > 0:
return x
elif x < 0:
return -x
else:
return 0
Practice Exercises
Exercise 1: List Transformations
Use lambda with map() and filter() to:
- Square all numbers in a list
- Filter out negative numbers
- Convert strings to uppercase
- Calculate string lengths
Exercise 2: Data Sorting
Use lambda with sorted() to sort:
- List of tuples by second element
- List of dictionaries by specific key
- Strings by length
- Numbers by their absolute value
Exercise 3: Mathematical Operations
Create lambda functions for:
- Area of circle (given radius)
- Compound interest calculation
- Temperature conversion
- Distance between two points
Exercise 4: Text Processing
Use lambda functions to:
- Count vowels in each word
- Filter palindromic words
- Sort words by vowel count
- Capitalize first letter of each word
Exercise 5: Custom Filters
Create complex filters using lambda:
- Filter products by price range and category
- Filter students by grade and attendance
- Filter dates by month and year
- Filter text by word length and content
Summary
Lambda functions are powerful tools for simple, one-off operations:
- Syntax:
lambda parameters: expression - Use with:
map(),filter(),sorted(), and other functions - Best for: Simple operations, one-time use
- Limitations: Single expression only, no statements
When to use lambda:
- Short, simple transformations
- Functions passed as arguments
- Quick calculations
- Data filtering and sorting
When to use regular functions:
- Complex logic
- Multiple statements
- Need for documentation
- Recursive operations
- Reusable code
Next: Data Structures - organizing your data efficiently! 📊