Skip to main content
Functional programming decomposes problems into a set of functions. This guide covers Python’s features for functional-style programming.

Key Concepts

Functional programming emphasizes:
  • Pure functions: Output depends only on input
  • Immutability: Avoid changing state
  • Higher-order functions: Functions that take/return functions
  • Composability: Combine simple functions into complex ones

Iterators

Basic Iterator Usage

An iterator returns data one element at a time:

Iterate Through Collections

List Comprehensions

Generator Expressions

Memory-Efficient Iteration

Generator vs List Comprehension

Generator Functions

Creating Generators

Use yield instead of return:

Infinite Generators

Generator State

Generators maintain state between calls:

Built-in Functions

map()

Apply function to every item:

filter()

Select items that match a condition:

enumerate()

Get index and value:

zip()

Combine multiple iterables:

any() and all()

Test iterator contents:

sorted()

Sort any iterable:

The itertools Module

Creating Iterators

The functools Module

reduce()

Cumulatively apply a function:

partial()

Create functions with pre-filled arguments:

lru_cache()

Cache function results:

Lambda Functions

Basic Usage

With Built-in Functions

When to avoid lambda:

The operator Module

Function equivalents of operators:

Practical Examples

Data Pipeline

Functional Data Processing

Composing Functions

Best Practices

When to use functional programming:
  • ✅ Data transformations and pipelines
  • ✅ Processing collections
  • ✅ Stateless operations
  • ✅ Parallel processing
  • ❌ Complex stateful logic
  • ❌ I/O heavy operations
  • ❌ When performance is critical (imperative may be faster)
Common pitfalls:
  1. Iterator exhaustion - iterators can only be used once
  2. Late binding in loops - lambda captures variables by reference
  3. Excessive nesting - deeply nested comprehensions are hard to read
  4. Overusing lambda - named functions are more readable

Summary

Key functional programming tools in Python:
  1. Iterators - process data one item at a time
  2. Generators - create iterators with yield
  3. List comprehensions - concise list creation
  4. Built-ins - map(), filter(), zip(), enumerate()
  5. itertools - combinatoric and infinite iterators
  6. functools - reduce(), partial(), higher-order functions
  7. operator - function equivalents of operators