__iter__
__iter__ is a Python special method that returns an iterator for an object.
Python Workout: 50 ten-minute exercises
A Python method that returns an iterator for an object, commonly returning the object itself when it is its own iterator.
- How it is used
- Makes custom objects usable in for loops by connecting them to Python’s iterator protocol.
- How deep it goes
- Explains __iter__ through classes, stateful __next__ methods, StopIteration, helper iterators, and generators.
- Examples
- Uses LoudIterator, MyEnumerate, repeated passes, and a bounded Circle generator expression.
- What you can do after
- Build custom iterable objects and select self, helper iterators, generator functions, or generator expressions for __iter__.
Read how Python Workout: 50 ten-minute exercises explains __iter__ →
Python Workout, Second Edition
The __iter__ method is Python's special method for returning an iterator associated with an iterable object.
- How it is used
- Connects custom objects to for loops, list comprehensions, and Python's iterator protocol.
- How deep it goes
- Explains dispatch through iter and next, iterator state, StopIteration, helper iterators, and generator-expression alternatives.
- Examples
- Demonstrates LoudIterator, Circle, MyEnumerate, and repeated iteration over a helper iterator.
- What you can do after
- Build custom iterable classes and diagnose exhausted self-iterators by tracing __iter__, __next__, and StopIteration.
Related concepts
- iteratorproduces · An iterator is an object or abstraction that provides successive values from a sequence or data source through a traversal protocol.
- iterableused by · An iterable is an object or value that provides or supports a protocol for producing its elements sequentially.
- iterator methodused by · An iterator method is an operation that returns an iterator for traversing the elements of a collection or iterable.
- generator expressionproduces · A generator expression is syntax that lazily produces successive values from an iterable without immediately constructing the complete result collection.
These guides are generated from the text of Manning books by Manning's knowledge graph and link to the sections they draw on. The full books are available on liveBook and at manning.com.

