Python Basics — Lambda & Functional Programming
Lambda & Functional Programming
Python supports a functional programming style through lambda expressions and built-in functions like map(), filter(), and reduce(). These tools let you write concise, expressive data transformations.
What You’ll Learn
| # | Topic | What You’ll Master |
|---|---|---|
| 1 | Lambda Expressions | Anonymous single-expression functions |
| 2 | map() Function | Transform every item in an iterable |
| 3 | filter() Function | Select items that match a condition |
| 4 | reduce() Function | Accumulate items into a single result |
| 5 | sorted() with Key | Custom sorting with key functions |
| 6 | Practice Exercises | Test your understanding |
Quick Preview
# Traditional approach
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
# Get squares of even numbers
result = []
for n in numbers:
if n % 2 == 0:
result.append(n ** 2)
print(result) # [4, 16, 36, 64, 100]
# Functional approach
result = list(map(lambda x: x ** 2, filter(lambda x: x % 2 == 0, numbers)))
print(result) # [4, 16, 36, 64, 100]
# Pythonic approach (list comprehension)
result = [n ** 2 for n in numbers if n % 2 == 0]
print(result) # [4, 16, 36, 64, 100]
When to Use Functional vs Imperative
| Approach | Best For | Example |
|---|---|---|
Lambda + map/filter |
Quick inline transformations | map(str.upper, words) |
| List comprehension | Most Python code (Pythonic) | [x**2 for x in nums] |
reduce() |
Accumulating into a single value | Sum, product, concatenation |
sorted() with key |
Custom sort orders | sorted(students, key=lambda s: s["gpa"]) |
| Regular functions | Complex logic, reusability | Multi-step processing |