ch7s1_LambdaFunctions
Lambda functions, also known as **anonymous functions**, are lightweight, single-expression functions defined without the `def` keyword.
Chapter 7: Functional Programming
Sub-Chapter: Lambda Functions — Anonymous and Expressive
Lambda functions, also known as anonymous functions, are lightweight, single-expression functions defined without the def keyword.
They are essential in functional programming for concise operations like transformation, filtering, and mapping — especially when a full function definition would be excessive.
🧱 1. Basic Syntax
A lambda function is defined using the lambda keyword, followed by parameters and a single expression.
lambda arguments: expression
Example:
double = lambda x: x * 2
print(double(5)) # Output: 10
Lambdas always return the value of their expression automatically — you do not use
return.
🔍 2. Lambda vs. Regular Functions
| Feature | Lambda Function | Regular Function (def) |
|---|---|---|
| Syntax | lambda x: x * 2 | def f(x): return x * 2 |
| Name | Anonymous (can be assigned) | Named by definition |
| Expressions | Single expression only | Multiple statements allowed |
| Return | Implicit | Explicit (return) |
| Scope | Inline / temporary | Persistent |
| Common use | Short, simple operations | Complex reusable logic |
Example comparison:
# Regular function
def add(x, y):
return x + y
# Equivalent lambda
add_lambda = lambda x, y: x + y
⚙️ 3. Common Functional Uses of Lambda
➤ Mapping (Transformation)
numbers = [1, 2, 3, 4, 5]
squares = list(map(lambda x: x ** 2, numbers))
print(squares) # [1, 4, 9, 16, 25]
➤ Filtering (Selection)
numbers = [1, 2, 3, 4, 5, 6]
evens = list(filter(lambda x: x % 2 == 0, numbers))
print(evens) # [2, 4, 6]
➤ Sorting (Custom Keys)
people = [("Alice", 25), ("Bob", 30), ("Charlie", 22)]
sorted_people = sorted(people, key=lambda p: p[1])
print(sorted_people)
# [('Charlie', 22), ('Alice', 25), ('Bob', 30)]
➤ Reduction (Aggregation)
from functools import reduce
numbers = [1, 2, 3, 4]
product = reduce(lambda x, y: x * y, numbers)
print(product) # 24
🧩 4. Advanced Lambda Expressions
Conditional Expressions
grade = lambda score: "Pass" if score >= 60 else "Fail"
print(grade(75)) # Pass
Multiple Arguments
combine = lambda a, b, c: f"{a}-{b}-{c}"
print(combine("2025", "10", "26")) # 2025-10-26
Nested Lambda
adder = lambda x: (lambda y: x + y)
add_five = adder(5)
print(add_five(10)) # 15
Using with any() or all()
numbers = [2, 4, 6, 8]
print(all(map(lambda x: x % 2 == 0, numbers))) # True
🧮 5. Practical Examples
Example 1 — Sorting a List of Dictionaries
employees = [
{"name": "Alice", "salary": 70000},
{"name": "Bob", "salary": 50000},
{"name": "Charlie", "salary": 90000}
]
sorted_employees = sorted(employees, key=lambda e: e["salary"], reverse=True)
print(sorted_employees[0]["name"]) # Charlie
Example 2 — Cleaning and Transforming Data
names = [" alice ", "BOB", " Charlie "]
cleaned = list(map(lambda n: n.strip().title(), names))
print(cleaned) # ['Alice', 'Bob', 'Charlie']
Example 3 — Functional Pipeline
data = [5, -2, 10, -7, 3]
# Filter positives, square them, and sum
result = sum(map(lambda x: x**2, filter(lambda x: x > 0, data)))
print(result) # 134
Example 4 — Custom Sorting with Conditions
files = ["file1.txt", "image.png", "data.csv", "README"]
sorted_files = sorted(files, key=lambda f: ('.' not in f, f))
print(sorted_files) # ['data.csv', 'file1.txt', 'image.png', 'README']
🔬 6. Closures and Lambdas
Lambdas can capture outer variables and create closures.
def make_multiplier(n):
return lambda x: x * n
double = make_multiplier(2)
triple = make_multiplier(3)
print(double(10)) # 20
print(triple(10)) # 30
🧠 7. Combining with Built-ins
| Function | Purpose | Lambda Example |
|---|---|---|
map() | Apply transformation | map(lambda x: x+1, data) |
filter() | Keep items matching condition | filter(lambda x: x>0, data) |
reduce() | Combine all items into one value | reduce(lambda a,b: a*b, data) |
sorted() | Sort by custom key | sorted(data, key=lambda x: -x) |
any() / all() | Logical checks | all(map(lambda x: x>0, nums)) |
min() / max() | Find min/max by rule | max(data, key=lambda x: x["age"]) |
🧮 8. Inline vs Named Lambdas — When to Use
✅ Use lambda when:
- The function is small, one-line, and used once.
- You’re passing a function as an argument (e.g., in
map,sorted, orfilter).
❌ Avoid lambda when:
- The logic is multi-step or requires debugging.
- Readability is important (prefer named functions).
Example of poor usage:
# Bad: too complex for lambda
compute = lambda x: (x**2 + 5) / (x - 2) if x != 2 else float("inf")
Better alternative:
def compute(x):
if x == 2:
return float("inf")
return (x**2 + 5) / (x - 2)
🧭 9. Visualization — Functional Data Flow
Raw Data → filter() → map() → reduce()
λ-condition λ-transform λ-aggregate
Example: Filter positives → square them → sum
🧾 10. Best Practices
✅ Keep lambdas short — one expression only.
✅ Use meaningful variable names even in lambdas.
✅ For readability, prefer named functions when logic grows.
✅ Combine with map(), filter(), or sorted() for clean, declarative code.
✅ Remember lambdas capture variables by reference, not by value.
🧠 Summary
- Lambdas are short, anonymous functions defined inline.
- Perfect for quick transformations, filtering, or mapping tasks.
- Core tools in functional programming alongside
map(),filter(), andreduce(). - Best used for concise, stateless operations — not complex logic.
By mastering lambdas, you unlock Python’s expressive functional style — making code more compact, elegant, and declarative.