Iterators & the Iterator Protocol — Free Python Tutorial
Learn Iterators & the Iterator Protocol in Python with a free, beginner-friendly tutorial, examples and practice for Indian students on Syllab.in.
TL;DR: Learn Iterators & the Iterator Protocol in Python with a free, beginner-friendly tutorial, examples and practice for Indian students on Syllab.in.
Written & reviewed by the Syllab.in Academic Team (CBSE/NCERT subject experts) · Updated
Iterators & the Iterator Protocol in Python
An iterator implements __iter__() and __next__() — the iterator protocol. Every for loop calls these behind the scenes. Iterators produce values lazily (one at a time), saving memory for large sequences.
Custom iterators let you create objects that behave like lists or ranges but compute values on demand. This is the foundation of Python's memory efficiency with large data.
iter() and next() are built-in functions that call __iter__ and __next__. Once exhausted, an iterator raises StopIteration — the for loop catches this to know when to stop.
Iterators & the Iterator Protocol — Syntax
class MyIter:
def __iter__(self): return self # required
def __next__(self):
# return next value OR raise StopIteration
raise StopIteration
Learn Iterators & the Iterator Protocol step by step with Syllab's free interactive Python tutorial — runnable code examples, practice exercises and instant AI feedback, all free with no signup. Explore the full Python course →