Conceptual
Login

Iterators and Itertools in Python

An iterator is an object implementing the iterator protocol, defined by the `__iter__` and `__next__` dunder methods, which enables traversal (iteration) over a sequence until exhaustion raises a `StopIteration` exception. An iterable is distinct from an iterator: an iterable is any object capable of producing an iterator via `__iter__`, while an iterator additionally implements `__next__` and, when asked for an iterator itself, returns itself rather than a new one. This distinction belongs to Python's data model within computer science/programming language theory, and generalizes further through the `itertools` module, which applies functional-programming principles—treating iterators as composable algebraic objects that can be combined (via functions like counting, repetition, accumulation, permutation, combination, chaining, filtering, and tuple-unpacking application) to express complex sequence transformations without explicit loops.