Skip to content

What is functional programming

Functional programming treats computation as the evaluation of functions avoiding shared state and mutable data. Python isn’t a pure functional language, is a multi-paradigm language that supports functional programming, but it has excellent functional tools. Key FP tools in Python include:

  • lambda — anonymous, single-expression functions
  • map(), filter(), reduce() — classic higher-order functions for transforming and aggregating data
  • List/dict/set comprehensions — a Pythonic, declarative way to build collections
  • functools module — utilities like functools.reduce(), functools.partial(), and functools.lru_cache()
  • Closures — functions that capture variables from their enclosing scope
  • Immutability via convention — Python has no enforced immutability, but tuple and frozenset are immutable types

A quick example comparing styles:

Imperative style
# ❌ Imperative style — how to do it
total = 0
for x in [1, 2, 3, 4, 5]:
if x % 2 == 0:
total += x ** 2
Functional style
# ✅ Functional style — what you want
from functools import reduce
total = reduce(lambda acc, x: acc + x,
map(lambda x: x**2,
filter(lambda x: x % 2 == 0, [1, 2, 3, 4, 5])))
# ✅ Pythonic functional style — most readable
total = sum(x**2 for x in [1, 2, 3, 4, 5] if x % 2 == 0)

Another example:

Imperative style
numbers = [1, 2, 3, 4, 5]
# ❌ Imperative style
squares = []
for n in numbers:
if n % 2 == 0:
squares.append(n ** 2)
Functional style
numbers = [1, 2, 3, 4, 5]
# ✅ Functional style
squares = list(map(lambda n: n ** 2, filter(lambda n: n % 2 == 0, numbers)))
# ✅ Pythonic functional style (comprehension)
squares = [n ** 2 for n in numbers if n % 2 == 0]

Python’s functional support is practical rather than pure, it doesn’t enforce immutability or guarantee tail-call optimization, so it’s best used selectively alongside OOP or procedural code rather than as an exclusive paradigm.

ConceptToolUse case
Transformmap(), comprehensionApply function to every element
Filterfilter(), comprehensionKeep elements matching condition
Foldreduce()Collapse iterable to single value
Fix argspartial()Pre-fill function arguments
Cachelru_cache, cacheMemoize pure functions
OverloadsingledispatchType-based dispatch
Fill comparisonstotal_orderingDefine one, get all
Capture stateClosureStateful function factories
Combine functionsCompositionBuild pipelines from small functions
ImmutabilityNamedTuple, frozen=TrueSafe, predictable data
Iteration toolsitertoolsEfficient, composable iteration

The Truly Final Complete Advanced Python Journey

Section titled “The Truly Final Complete Advanced Python Journey”
TopicStatus
OOP & Dunder Methods
Functional Programming
Iterators & Generators
Decorators
Context Managers
Advanced Error Handling
Advanced Data Structures
Concurrency & Async
Metaclasses & Descriptors
Memory & Performance
Modules & Packaging
Type Hints & Static Analysis