I spent way too long writing object-oriented Python before I realized I could just... not do that. Functions can be values. Data doesn't need to mutate. The code gets smaller.
Python lets you write functional code without committing to it like Haskell does. That's useful.
Python isn't Haskell. That's fine.
Python is not a pure functional language. It's a practical language that lets you write in multiple styles. You can do OOP. You can do procedural scripts. You can also write code that acts functional: small pure-ish functions, minimal mutation, and pipelines.
The basic principles are simple:
- Immutability: don't mutate data unless you have a good reason
- Pure functions: same input, same output, no side effects
- First-class functions: functions can be values
- Higher-order functions: functions that take/return functions
- Recursion: useful sometimes (Python's recursion limit makes it a special occasion tool)
If you've ever debugged a state bug where the variable was "fine" three lines ago, functional style feels like a relief. Less state. Less "who touched this and why."
Lambda functions
lambda is for small, local behavior. One expression. No statements. If you're doing anything that needs comments or line breaks, write a def.
square = lambda x: x**2
square(5) # 25
Lambda is useful for sorting:
pairs = [(1, "one"), (3, "three"), (2, "two"), (4, "four")]
sorted(pairs, key=lambda pair: pair[1])
## [(4, 'four'), (1, 'one'), (3, 'three'), (2, 'two')]
That's clean. It reads like intent.
Map and filter basics
map applies a function to each item. filter keeps items that pass a predicate. Both return iterators in Python 3, which means they're lazy.
nums = [1, 2, 3, 4, 5]
list(map(lambda x: x**2, nums))
## [1, 4, 9, 16, 25]
Converting Celsius to Fahrenheit:
celsius = [0, 10, 20, 30, 40]
to_f = lambda c: (c * 9/5) + 32
list(map(to_f, celsius))
## [32.0, 50.0, 68.0, 86.0, 104.0]
Filtering evens:
nums = list(range(1, 11))
list(filter(lambda x: x % 2 == 0, nums))
## [2, 4, 6, 8, 10]
Filtering "adults" from dictionaries:
people = [{"name": "Ada", "age": 17}, {"name": "Linus", "age": 31}]
list(filter(lambda p: p["age"] >= 18, people))
## [{'name': 'Linus', 'age': 31}]
Chaining map and filter gets unreadable fast. Also, once you consume an iterator, it's gone. You'll trip on that once, stare at an empty list, then remember forever. For more advanced lazy iteration patterns, check out mastering Python's itertools for efficient data processing.
Reduce
reduce moved to functools in Python 3. Which should tell you something.
from functools import reduce
nums = [1, 2, 3, 4, 5]
reduce(lambda x, y: x * y, nums)
## 120
Example with totals:
sales = [
{"product": "a", "price": 2.5, "qty": 2},
{"product": "b", "price": 1.2, "qty": 3},
]
total = reduce(lambda acc, s: acc + (s["price"] * s["qty"]), sales, 0.0)
## 8.6
But sum() is usually clearer:
total = sum(s["price"] * s["qty"] for s in sales)
Python has the functional tools, but the normal Python way is often easier to read.
Combining map, filter, and reduce
Say you have student grades and you want:
1) average per student
2) keep high performers
3) compute overall average of high performers
from functools import reduce
students = {
"Ava": [92, 88, 95],
"Ben": [70, 65, 72],
"Cam": [90, 91, 89],
"Dee": [84, 86, 83],
}
avg = lambda xs: sum(xs) / len(xs)
## map: compute averages
avgs = list(map(lambda kv: (kv[0], avg(kv[1])), students.items()))
## [('Ava', 91.666...), ('Ben', 69.0), ('Cam', 90.0), ('Dee', 84.333...)]
## filter: keep > 85
high = list(filter(lambda kv: kv[1] > 85, avgs))
## [('Ava', ...), ('Cam', 90.0)]
## reduce: overall average of high performers
overall = reduce(lambda acc, kv: acc + kv[1], high, 0.0) / len(high)
## ~90.83
This works, but I probably wouldn't ship it like this. A comprehension is likely clearer. Still, the shape is useful: transform - select - aggregate. That pattern shows up in data work, ML feature prep, and plenty of boring business logic.
Two advanced tools I actually use
partial: freeze arguments without writing wrappers
from functools import partial
def multiply(a, b):
return a * b
double = partial(multiply, 2)
double(21) # 42
Composition: build tiny functions and glue them
def compose(*funcs):
def inner(x):
for f in reversed(funcs):
x = f(x)
return x
return inner
add_one = lambda x: x + 1
double = lambda x: x * 2
f = compose(double, add_one)
f(3) # 8
Not complicated. Just small functions that do one thing.
Use functional style when it helps
Functional style is great for local clarity: fewer side effects, less mutation, and code you can reason about without rereading the whole file.
If the functional version reads clean, keep it. If it turns into a wall of lambdas and parentheses, rewrite it into plain Python. You're not failing a purity test. You're trying to ship code that you can debug on a Tuesday.
-Sethers