Skip to main content

Iterators and Generators

The Iterator Protocol

0:00
LearnStep 1/3

Mastering the Iterator Protocol

In Python, iteration is powered by the Iterator Protocol. This protocol consists of two methods: __iter__ and __next__. Understanding these allows you to create efficient, memory-friendly custom sequences.

Iterables vs. Iterators

An iterable is an object capable of returning its members one at a time (e.g., lists, tuples, strings). An iterator is the object that actually performs the iteration, maintaining its own internal state.

python

Custom Iterators

To make a class an iterator, you must implement __iter__ (which typically returns self) and __next__ (which returns the next item or raises StopIteration).

python

The iter() Sentinel Pattern

The iter() function can take a second argument called a sentinel. When used this way, the first argument must be a callable. The iterator will call this callable until it returns the sentinel value.

python