liveBook · Manning

__iter__

__iter__ is a Python special method that returns an iterator for an object.

How 2 Manning books explain it

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.

Read how Python Workout, Second Edition explains __iter__ →

Related concepts

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.