0Pricing
Python Academy · Lesson

The Iterator Protocol

Understand __iter__ and __next__.

What Is Iteration?

Whenever you write a for loop over a list, string, or dict, Python is using the iterator protocol behind the scenes.

An object you can loop over is called an iterable. The thing that actually produces values one at a time is called an iterator.

for ch in 'abc':
    print(ch)

iter() and next()

Two built-in functions drive iteration:

  • iter(obj) asks an iterable for its iterator.
  • next(it) asks the iterator for the next value.

When there are no more values, next() raises StopIteration.

it = iter([10, 20, 30])
print(next(it))
print(next(it))
print(next(it))

All lessons in this course

  1. The Iterator Protocol
  2. Generator Functions
  3. Generator Expressions
  4. yield from and Delegation
← Back to Python Academy