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
# Create a list of squares
squares = [x**2 for x in range(10)]
# [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
# Cartesian product
pairs = [(x, y) for x in [1, 2, 3] for y in ['a', 'b']]
# [(1, 'a'), (1, 'b'), (2, 'a'), (2, 'b'), (3, 'a'), (3, 'b')]
Generator Expressions
Memory-Efficient Iteration
Generator vs List Comprehension
Generator Functions
Creating Generators
Useyield 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
import itertools
# count() - infinite counter
for i in itertools.count(10, 2):
if i > 20:
break
print(i) # 10, 12, 14, 16, 18, 20
# cycle() - repeat sequence infinitely
counter = 0
for item in itertools.cycle(['a', 'b', 'c']):
if counter >= 5:
break
print(item)
counter += 1
# a, b, c, a, b
# repeat() - repeat element
list(itertools.repeat('hello', 3))
# ['hello', 'hello', 'hello']
import itertools
# combinations() - all r-length combinations
list(itertools.combinations([1, 2, 3], 2))
# [(1, 2), (1, 3), (2, 3)]
# permutations() - all r-length permutations
list(itertools.permutations([1, 2, 3], 2))
# [(1, 2), (1, 3), (2, 1), (2, 3), (3, 1), (3, 2)]
# product() - cartesian product
list(itertools.product([1, 2], ['a', 'b']))
# [(1, 'a'), (1, 'b'), (2, 'a'), (2, 'b')]
import itertools
def is_even(x):
return x % 2 == 0
# filterfalse() - opposite of filter()
list(itertools.filterfalse(is_even, range(10)))
# [1, 3, 5, 7, 9]
# takewhile() - take while predicate is true
list(itertools.takewhile(lambda x: x < 5, range(10)))
# [0, 1, 2, 3, 4]
# dropwhile() - drop while predicate is true
list(itertools.dropwhile(lambda x: x < 5, range(10)))
# [5, 6, 7, 8, 9]
import itertools
# chain() - combine multiple iterators
list(itertools.chain([1, 2], [3, 4], [5, 6]))
# [1, 2, 3, 4, 5, 6]
# islice() - slice an iterator
list(itertools.islice(range(10), 2, 8, 2))
# [2, 4, 6]
# tee() - split iterator into n independent iterators
it1, it2 = itertools.tee(range(5), 2)
list(it1) # [0, 1, 2, 3, 4]
list(it2) # [0, 1, 2, 3, 4]
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
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)
Summary
Key functional programming tools in Python:- Iterators - process data one item at a time
- Generators - create iterators with
yield - List comprehensions - concise list creation
- Built-ins -
map(),filter(),zip(),enumerate() - itertools - combinatoric and infinite iterators
- functools -
reduce(),partial(), higher-order functions - operator - function equivalents of operators
