Glossary

Iterator

An iterator is any object that implements the iterator protocol: a __next__() method that returns the next item in a sequence (or raises StopIteration when exhausted) and an __iter__() method that returns the iterator itself. Iterators are the engine behind Python's for loop: when you write for x in obj, Python calls iter(obj) to get an iterator, then repeatedly calls next() on it until StopIteration is raised.

Many Python objects are iterable (they have an __iter__ method that returns an iterator) but are not themselves iterators. A list is iterable — you can loop over it multiple times — but each loop creates a fresh iterator. A generator, by contrast, is its own iterator and can only be consumed once. This distinction matters when you need to make multiple passes over data.

The iterator protocol is Python's universal abstraction for sequential data access. Files, range objects, enumerate, zip, map, filter, dictionary views, and database cursors all produce iterators. The itertools module provides a rich toolkit of iterator combinators — chain, islice, product, groupby, count, cycle, and many more — that compose lazily without materialising intermediate collections.

Related terms: Generator, Iterable, Itertools

Discussed in:

This site is currently in Beta. Please email Chris Paton (cpaton@gmail.com) with any suggestions, questions or comments.