Lambda Functions and Functional Programming
Concise Anonymous Functions — Solving Problems with One Line of Code
What is a Lambda Function?
A Lambda function is an anonymous function (function without a name), used for simple one-time operations.
Syntax:
python
lambda parameters: expressionComparison:
python
# Regular function
def square(x):
return x ** 2
# Lambda function (equivalent)
square = lambda x: x ** 2
print(square(5)) # 25Basic Usage
Example 1: Simple Operations
python
# Addition
add = lambda x, y: x + y
print(add(3, 5)) # 8
# BMI calculation
bmi = lambda weight, height: weight / (height ** 2)
print(bmi(70, 1.75)) # 22.86
# Check if adult
is_adult = lambda age: age >= 18
print(is_adult(25)) # TrueExample 2: Combined with Built-in Functions
python
# sorted() + lambda
students = [
{'name': 'Alice', 'age': 25, 'gpa': 3.8},
{'name': 'Bob', 'age': 22, 'gpa': 3.5},
{'name': 'Carol', 'age': 24, 'gpa': 3.9}
]
# Sort by GPA
sorted_by_gpa = sorted(students, key=lambda s: s['gpa'], reverse=True)
for s in sorted_by_gpa:
print(f"{s['name']}: {s['gpa']}")
# Sort by age
sorted_by_age = sorted(students, key=lambda s: s['age'])map(), filter(), reduce()
1. map(): Apply Function to Each Element
python
# Regular approach
incomes = [50000, 60000, 75000, 80000]
incomes_after_tax = []
for income in incomes:
incomes_after_tax.append(income * 0.75)
# Using map + lambda
incomes_after_tax = list(map(lambda x: x * 0.75, incomes))
print(incomes_after_tax) # [37500, 45000, 56250, 60000]
# List comprehension (more Pythonic)
incomes_after_tax = [x * 0.75 for x in incomes]Social Science Application:
python
# Income log transformation
import math
incomes = [45000, 60000, 75000, 90000]
log_incomes = list(map(lambda x: math.log(x), incomes))
# Normalize scores
scores = [85, 92, 78, 88]
mean = sum(scores) / len(scores)
std_scores = list(map(lambda x: (x - mean) / 10, scores))2. filter(): Filter Elements
python
ages = [18, 25, 16, 30, 15, 40, 12, 35]
# Filter adults
adults = list(filter(lambda age: age >= 18, ages))
print(adults) # [18, 25, 30, 40, 35]
# Filter high earners
incomes = [45000, 75000, 120000, 55000, 95000]
high_earners = list(filter(lambda x: x > 70000, incomes))
print(high_earners) # [75000, 120000, 95000]
# List comprehension (more recommended)
adults = [age for age in ages if age >= 18]3. reduce(): Cumulative Calculation
python
from functools import reduce
# Calculate product
numbers = [1, 2, 3, 4, 5]
product = reduce(lambda x, y: x * y, numbers)
print(product) # 120
# Find maximum value
scores = [85, 92, 78, 95, 88]
max_score = reduce(lambda a, b: a if a > b else b, scores)
print(max_score) # 95
# But better to use built-in function
max_score = max(scores)Real-World Cases
Case 1: Data Cleaning Pipeline
python
# Raw data
raw_incomes = [50000, -1000, 75000, 0, 120000, 9999999, 60000]
# Cleaning pipeline
clean_incomes = list(
filter(lambda x: 0 < x < 1000000, # Filter valid values
map(lambda x: round(x, -3), # Round to thousands
raw_incomes))
)
print(clean_incomes) # [50000, 75000, 120000, 60000]Case 2: Sort by Multiple Criteria
python
respondents = [
{'id': 1, 'age': 30, 'income': 75000},
{'id': 2, 'age': 25, 'income': 85000},
{'id': 3, 'age': 25, 'income': 70000},
{'id': 4, 'age': 30, 'income': 90000}
]
# Sort by age first, then by income
sorted_data = sorted(respondents, key=lambda r: (r['age'], r['income']))
for r in sorted_data:
print(f"ID{r['id']}: {r['age']} years old, ${r['income']:,}")Case 3: Dynamically Generate Functions
python
def make_multiplier(n):
"""Return a function that multiplies by n"""
return lambda x: x * n
# Create different multiplier functions
double = make_multiplier(2)
triple = make_multiplier(3)
multiply_by_10 = make_multiplier(10)
print(double(5)) # 10
print(triple(5)) # 15
print(multiply_by_10(5)) # 50
# Application: Different tax rate calculators
def make_tax_calculator(rate):
return lambda income: income * rate
tax_low = make_tax_calculator(0.10)
tax_mid = make_tax_calculator(0.20)
tax_high = make_tax_calculator(0.30)
income = 100000
print(f"Low tax rate: ${tax_low(income):,.0f}")
print(f"Mid tax rate: ${tax_mid(income):,.0f}")
print(f"High tax rate: ${tax_high(income):,.0f}")Lambda vs Regular Functions
| Feature | Lambda | Regular Function |
|---|---|---|
| Syntax | lambda x: x**2 | def f(x): return x**2 |
| Name | Anonymous | Named |
| Complexity | Single-line expression | Multi-line |
| Documentation | Cannot add | Can add docstring |
| Use Cases | Simple, one-time | Complex, reusable |
When to Use Lambda?
- ✅ Simple one-time operations
- ✅ Passed as arguments (
sorted(key=...)) - ✅ Simple logic in map/filter
When to Use Regular Function?
- ✅ Complex logic (multiple lines)
- ✅ Needs documentation
- ✅ Needs to be reused
List Comprehension vs Lambda
For most cases, list comprehensions are more Pythonic than lambda:
python
numbers = [1, 2, 3, 4, 5]
# Using map + lambda
squares = list(map(lambda x: x**2, numbers))
# Using list comprehension (better)
squares = [x**2 for x in numbers]
# Using filter + lambda
evens = list(filter(lambda x: x % 2 == 0, numbers))
# Using list comprehension (better)
evens = [x for x in numbers if x % 2 == 0]Common Pitfalls
Pitfall 1: Variable Binding in Closures
python
# ❌ Wrong example
functions = []
for i in range(3):
functions.append(lambda x: x + i)
print(functions[0](10)) # Expected 10, actual 12
print(functions[1](10)) # Expected 11, actual 12
print(functions[2](10)) # Expected 12, actual 12
# All functions use the final value of i (2)
# ✅ Correct approach: Use default parameters
functions = []
for i in range(3):
functions.append(lambda x, i=i: x + i)
print(functions[0](10)) # 10
print(functions[1](10)) # 11
print(functions[2](10)) # 12Pitfall 2: Overuse Leading to Unreadable Code
python
# ❌ Hard to understand
result = list(filter(lambda x: x[1] > 50000 and x[2] < 40,
map(lambda p: (p['name'], p['income'], p['age']),
[r for r in data if r['gender'] == 'M'])))
# ✅ Clear approach
male_respondents = [r for r in data if r['gender'] == 'M']
high_income_young = [
(r['name'], r['income'], r['age'])
for r in male_respondents
if r['income'] > 50000 and r['age'] < 40
]Practice Exercises
Exercise 1: Using Lambda for Sorting
python
students = [
('Alice', 25, 3.8),
('Bob', 22, 3.5),
('Carol', 24, 3.9),
('David', 23, 3.6)
]
# Tasks: Sort by:
# 1. GPA from high to low
# 2. Age from low to high
# 3. Name alphabeticallyExercise 2: Data Transformation
python
incomes = [45000, 60000, 75000, 90000, 120000]
# Using map + lambda:
# 1. Calculate after-tax income (25% tax rate)
# 2. Convert to tens of thousands (divide by 10000)
# 3. Keep 1 decimal placeExercise 3: Comprehensive Application
python
data = [
{'name': 'Alice', 'age': 25, 'score': 85},
{'name': 'Bob', 'age': 30, 'score': 55},
{'name': 'Carol', 'age': 28, 'score': 92},
{'name': 'David', 'age': 22, 'score': 78}
]
# Tasks:
# 1. Filter passing students (score >= 60)
# 2. Sort by score from high to low
# 3. Keep only name and scoreNext Steps
In the next section, we'll learn about modules and package management, understanding how to organize and import code.
Continue!