🎉 75% of content is free forever — Unlock Premium from $10/mo →
CW
NEWSLIVESearch All Content
đŸ’ŧ Servicesâ„šī¸ Aboutâœ‰ī¸ ContactView Pricing Plansfrom $10

Python Iterators: Iterables, Sentinels, and Lazy Sequences

Python IterationđŸŸĸ Free Lesson

Prerequisites

  • !The for loop and the iterator protocol
  • !Generators and the yield keyword

What You'll Learn

  • 1Separate the iterable and iterator roles in the Python protocol
  • 2Implement a stateful iterator that raises StopIteration correctly
  • 3Design stop conditions with sentinels, flags, and lengths
  • 4Make a container safely re-usable with several concurrent loops
  • 5Choose between a hand-written iterator, a generator, and a list

Most Python code iterates without ever thinking about the machinery underneath: for calls one method, gets numbers back, and stops when something raises an exception. When you need to feed data from a file line by line, walk a tree in a custom order, or replay a stream without loading it all, that hidden protocol becomes your design surface. This lesson breaks the protocol into its two roles, shows how stop conditions are really expressed, and gives you patterns for iterators that behave well under repeated and nested use.

Two roles, two methods, one protocol

The confusion that trips up most people building custom iteration is treating iteration as a single thing. It is two. An iterable is any object that can produce an iterator, and it implements __iter__, which must return an iterator. An iterator is the object that actually yields items, and it implements __next__, which returns one item per call and raises StopIteration when the sequence is exhausted.

RoleMethod it definesWhat the method must returnWho calls it
Iterable (list, tuple, str, custom)__iter__A fresh iterator each timefor, iter(), in
Iterator (file, generator, range cursor)__next__The next item or raises StopIterationnext()
Container__len__, __contains__Length or membership resultlen(), in
Sequence fallback__getitem__ with integer indexesItem at index until IndexErrorOld-style iteration

The payoff of the split is that one iterable can be looped over many times in parallel. A list hands you the same elements through a new cursor each call, so two for loops over the same list never interfere. An iterator, by contrast, is single-use: after it raises StopIteration it is spent, and calling iter() on it simply returns itself. That asymmetry is worth memorising because it explains why you cannot restart a file object or a generator by looping over it again.

State machines, not collections

An iterator holds only enough state to know where it is. Implementing one is straightforward, and the discipline is in keeping the state minimal and the stop condition honest.

python
class Window:
    """Yield overlapping pairs from an iterable: (a, b), (b, c), ..."""

    def __init__(self, source):
        self._source = iter(source)
        self._prev = None
        self._started = False

    def __iter__(self):
        return self

    def __next__(self):
        for item in self._source:
            if not self._started:
                self._started = True
                self._prev = item
                continue
            pair = (self._prev, item)
            self._prev = item
            return pair
        raise StopIteration


print(list(Window(range(5))))   # [(0, 1), (1, 2), (2, 3), (3, 4)]

Two details deserve attention. __iter__ returns self, which is correct for an object that is itself an iterator; a container would instead create a new cursor. And the loop reads lazily from self._source, so the window never materialises the whole input. Because StopIteration is raised from __next__, the for loop terminates silently and no error reaches your code.

Stop conditions: length, flag, or sentinel

There is no single blessed way to end an iteration. Choose the mechanism that matches what you actually know at runtime.

Stop conditionBest whenCostExample
Input exhaustedWrapping another iteratorNoneThe window above
Fixed countYou know the run lengthOne counterBatcher of size n
Sentinel valueItems come from a protocol that uses a markerOne comparisonReading until None
Predicate failsThe data itself signals a boundaryOne test per itemRead while rows validate
External flagAnother thread or task signals shutdownThread-safe checkStreaming consumer

Sentinels deserve a special mention because they keep the caller simple: the producing side appends one marker, and every consumer stops at the same place. The risk is ambiguity, so pick a marker that cannot appear in valid data, and document it. When the marker can legitimately occur, prefer a length prefix or an explicit end flag over guessing.

Containers that survive being looped over twice

A classic bug is returning self from __iter__ on an object that stores iteration state in instance attributes. The first for loop exhausts it, and the second loop silently produces nothing. The fix is to separate the container from the cursor.

python
class CircularBuffer:
    def __init__(self, items, laps=1):
        self._items = list(items)
        self._laps = laps

    def __iter__(self):
        return self._cursor()

    def _cursor(self):
        for _ in range(self._laps):
            for item in self._items:
                yield item


buf = CircularBuffer(["a", "b", "c"], laps=2)
first = list(buf)
second = list(buf)
print(first)    # ['a', 'b', 'c', 'a', 'b', 'c']
print(second)   # ['a', 'b', 'c', 'a', 'b', 'c']

Because __iter__ delegates to a generator, every loop starts from scratch and two loops can run at the same time without stepping on each other. This pattern also lets you memoise expensive traversal: store results on the container, not in the cursor, and each pass can reuse them while still returning an independent iterator.

Composing iterators without exploding memory

Standard library tools let you build pipelines from small pieces. itertools.islice takes a window, itertools.chain concatenates sources lazily, zip and map fuse steps, and itertools.tee splits one iterator into two when you genuinely need to look ahead. The discipline is to keep the pipeline lazy end to end.

python
import itertools as it

def rows():
    for i in range(1000000):
        yield {"id": i, "active": i % 7 == 0}

active = (r["id"] for r in rows() if r["active"])
capped = it.islice(active, 5)
print(list(capped))          # [0, 7, 14, 21, 28]

pairs = zip(it.count(0), rows())
print(next(pairs))           # (0, {'id': 0, 'active': True})

Every line above touches at most one record at a time. Contrast that with building a filtered list first: you would hold every active row in memory even though you only needed five. The practical rule is that list comprehensions are for materialising small, reused results, and generator expressions are for passing data through a pipeline that will be consumed once.

The habits that keep iteration predictable

Reliable iterators share a few properties that are easy to test for. They are lazy, so nothing expensive happens until next() is called. They are re-entrant when they are containers, so nested loops work. They raise StopIteration exactly once and never yield a value after that. And they do not mutate their source while another cursor walks it, which is the one rule that silently corrupts data when violated.

When you write a class that only ever yields one pass over fixed data, ask whether a generator function would say the same thing in ten lines. Reserve hand-written __next__ methods for state that is genuinely awkward as a local variable: resumable parsing, multi-source merges, or cursors that must be shared with C extensions.

Testing an iterator without a debugger

Iterator bugs are easy to miss because a bad stop condition usually produces too few items rather than a crash. Three cheap checks catch almost everything. First, convert to a list and compare the length against a hand-counted expectation, which exposes off-by-one errors at the boundary. Second, exhaust the iterator once and then ask for one more item, confirming that StopIteration is raised rather than a sentinel value being yielded. Third, run the same container through two nested loops and assert both see the full sequence, which proves the object is genuinely re-iterable.

python
import pytest

def test_window_is_reusable():
    buf = CircularBuffer([1, 2, 3], laps=2)
    assert list(buf) == [1, 2, 3, 1, 2, 3]
    assert list(buf) == list(buf)

def test_exhaustion_is_explicit():
    cursor = iter(Window([1, 2]))
    assert list(cursor) == [(1, 2)]
    with pytest.raises(StopIteration):
        next(cursor)

These tests cost a few lines and remove whole categories of production surprises.

Common Mistakes

Returning self from __iter__ while storing progress in instance attributes

Fix: Keep progress in a separate cursor object or a generator so each loop gets an independent pass.

Forgetting to raise StopIteration and letting the function fall through to None

Fix: End __next__ with an explicit raise StopIteration; silently returning None corrupts loops that expect typed items.

Looping over an iterator twice and getting an empty second pass

Fix: Call iter() on the container, or design the object as a re-iterable container that mints a fresh generator per call.

Converting a huge lazy pipeline to a list out of habit

Fix: Keep generator expressions and itertools chains lazy until you genuinely need random access or multiple passes.

Best Practices

  • Document whether your object is an iterable container or a one-shot iterator
  • Wrap third-party sources in iter() inside your __next__ so any iterable can be the input
  • Prefer itertools over hand-rolled nesting when a one-line combination expresses the same thing
  • Test iteration by looping twice and by running two loops concurrently
  • Yield small tuples or named records rather than index pairs that callers must decode

Key Takeaways

  • An iterable defines __iter__ and an iterator defines __next__; the split enables many independent loops
  • StopIteration is the normal, silent end of iteration, not an error condition
  • Choose stop conditions deliberately: count, sentinel, predicate, or external flag
  • Keep state on the container and pass state through a generator cursor to stay re-usable
  • Lazy pipelines with generators and itertools process large inputs in constant memory
CW

ChatWhole Learn Editorial Team

Written by experienced data scientists, software engineers, and educators. All content is reviewed by industry professionals to ensure accuracy and relevance.

Last reviewed: 2026-10-12

—
☆☆☆☆☆
0 ratings

Rate & Feedback

Continue Learning

Suggested next tutorials based on this topic

Need Expert Python Help?

Get personalized tutoring, project support, or professional consulting.

Advertisement