Explain the Python Iterators
Ask by ICSM Computer
Updated 02 Oct 2025
It follows the iterator protocol, which means it must implement two methods:
__iter__()→ returns the iterator object itself.__next__()→ returns the next item in the sequence. If no items are left, it raises aStopIterationexception.Example 1: Basic Iterator
Here,
iter()turns the list into an iterator, andnext()fetches items one by one.Example 2: Custom Iterator
You can build your own iterator class by defining
__iter__()and__next__():Output:
Why Iterators Matter
forloops, comprehensions, and many built-ins use iterators under the hood.Iterators vs Iterables
__iter__().__iter__()and__next__().Example: