liveBook · Manning

Iterator

As explained in Python Workout, Second Edition

The iterator protocol is the Python protocol through which an object supplies successive values for iteration.

An iterator convention lets objects supply successive values to for loops and many functions. An iterable implements __iter__, which returns an iterator; that iterator implements __next__ and raises StopIteration when exhausted. section 11.1 section 11.5

A for loop calls iter on its target, repeatedly calls next on the returned iterator, and stops when StopIteration is raised. The object controls what each iteration produces: strings yield characters, dictionaries yield keys, and files yield lines. section 11.2

Implement the convention in three practical ways:

  • Add __iter__ and __next__ to a class, storing iteration state such as the current index on the object. section 11.7
  • Separate an iterable from a helper iterator when the same object should support independent, repeatable loops. section 11.7
  • Use generator functions or generator expressions when they express the iteration more directly or avoid constructing a full list. section 11.26 section 11.27

Repeating values with a custom iterator

A Circle object can return elements from a sequence a specified number of times, repeating the sequence as necessary. For example, list(Circle('abc', 5)) produces five values before the iterator ends. section 11.10

for i in 'abcd':
    print(i)     #1

A short for-loop example makes the protocol’s user-facing behavior concrete before implementation details are introduced. section 11.1

How Python Workout, Second Edition covers it

How deep it goes
Defines __iter__, __next__, and StopIteration, then works through iterator state, helper classes, generators, and exhaustion behavior.
Examples
Uses strings, lists, dictionaries, files, a repeating Circle iterator, and a multi-file line generator as concrete cases.
What it assumes
Assumes basic Python objects, classes, functions, and loops while explaining iterable and iterator behavior explicitly.
What you can do after
Build iterable classes, helper iterators, generator functions, and generator expressions, then diagnose exhausted or non-iterable loop targets.
How it connects
Connects iterable objects with for loops, comprehensions, generators, generator expressions, files, dictionaries, enumerate, range, and itertools.

Also explained in

Compare how 15 books explain iterator →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Python Workout, Second Edition. The section links point to the parts of the book it draws on.