On this page
Iterators and Generators
Prev: Advanced Python Internals | Up: Advanced Python Internals | Next: Decorators and Closures
Rel: itertools, iter, next, collections
Ref: docs.python.org — Iterators | docs.python.org — itertools
Tags: #public #python3 #tutorials #internals #iterators #generators
Contents
- > The Iterator Protocol (`__iter__` & `__next__`)
- > Generators (`yield` & `yield from`)
- > Generator Expressions & Lazy Pipelines
- > `itertools` Building Blocks
The Iterator Protocol (__iter__ & __next__)
- An iterable implements
__iter__()returning an iterator. - An iterator implements both
__iter__()(returningself) and__next__()(returning the next item or raisingStopIteration).
class Countdown:
def __init__(self, start: int) -> None:
self.current = start
def __iter__(self) -> "Countdown":
return self
def __next__(self) -> int:
if self.current <= 0:
raise StopIteration
value = self.current
self.current -= 1
return value
print(list(Countdown(4))) # [4, 3, 2, 1]
Generators (yield & yield from)
Functions containing yield compile into generator functions that suspend and resume execution frame state lazily. yield from delegates iteration (and .send() / .throw() / return values) to a sub-iterator.
def fibonacci():
a, b = 0, 1
while True:
yield a
a, b = b, a + b
def flatten(nested):
for item in nested:
if isinstance(item, list):
yield from flatten(item)
else:
yield item
print(list(flatten([1, [2, [3, 4]], 5]))) # [1, 2, 3, 4, 5]
Generator Expressions & Lazy Pipelines
Generator expressions (expr for x in iterable) consume $O(1)$ memory regardless of stream size, allowing composable streaming pipelines.
lines = ["INFO ok", "ERROR disk full", "ERROR timeout", "INFO done"]
errors = (line for line in lines if line.startswith("ERROR"))
messages = (line.removeprefix("ERROR ") for line in errors)
print(list(messages)) # ['disk full', 'timeout']
itertools Building Blocks
[[stdlib_module/itertools|itertools]] implements fast C-level lazy iterator combinators (islice, chain, groupby, accumulate, batched, product, combinations).
import itertools
# First 8 Fibonacci numbers without materializing an infinite sequence
first_eight = list(itertools.islice(fibonacci(), 8))
print(first_eight) # [0, 1, 1, 2, 3, 5, 8, 13]
# Fixed-size batching (Python 3.12+)
print(list(itertools.batched(range(1, 8), 3))) # [(1, 2, 3), (4, 5, 6), (7,)]
# Running totals
print(list(itertools.accumulate([10, 20, 30]))) # [10, 30, 60]
Linked from
- tuts/javascript/tutorials/iterators_and_generators
- tuts/programming/paradigms/functional_programming
- tuts/python3/tutorials
- tuts/python3/tutorials/advanced_python_internals
- tuts/python3/tutorials/advanced_python_internals/decorators_and_closures
- tuts/python3/tutorials/advanced_python_internals/iterators_and_generators
Related notes
- tuts/python3/tutorials/advanced_python_internals Linked here; links to this page; shared tags: #internals, #tutorials
- tuts/python3/tutorials/advanced_python_internals/decorators_and_closures Linked here; links to this page; shared tags: #internals, #tutorials
- tuts/javascript/tutorials/iterators_and_generators links to this page; shared tags: #generators, #iterators, #tutorials
- tuts/python3/tutorials links to this page; shared tags: #tutorials
- tuts/programming/paradigms/functional_programming links to this page
- tuts/python3/__builtins__/iter Linked here
- tuts/python3/__builtins__/next Linked here
- tuts/python3/stdlib_module/collections Linked here
- tuts/python3/stdlib_module/itertools Linked here
- tuts/javascript/tutorials/prototype_chain_and_new_flow shared tags: #internals, #tutorials