Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Learn The Iterator Protocol | Python Iterators
Functional Programming Concepts in Python

bookThe Iterator Protocol

Swipe to show menu

In Python, the iterator protocol is a set of methods that allows objects to be iterated over, making them compatible with constructs like for loops. The two essential methods involved are __iter__ and __next__. When you use a for loop on an object, Python internally calls the object's __iter__ method to retrieve an iterator. This iterator must have a __next__ method, which returns the next item in the sequence each time it is called. When there are no more items, __next__ must raise a StopIteration exception to signal the end of the sequence.

1234567891011121314151617181920212223242526
class SquaresIterator: # Initialize with the number of squares to generate def __init__(self, limit): self.limit = limit self.current = 0 # Return the iterator object (itself) def __iter__(self): return self # Return the next square, or stop if done def __next__(self): if self.current < self.limit: # Calculate square result = self.current ** 2 # Move to next number self.current += 1 return result # If no more items else: raise StopIteration for square in SquaresIterator(5): print(square)
copy

__init__ - Setup Phase

When the iterator is created it receives a:

  • limit → how many numbers to generate;

  • It sets current = 0 → the starting point;

  • It prepares everything needed for iteration.

__iter__ - Making It Iterable

  • Returns self (the object itself);
  • This is what allows you to use it in a for loop.

__next__ - Producing Values

This method runs every time the loop asks for the next item:

  • If current < limit:
    • Calculate current²;
    • Increase current by 1;
    • Return the result.
  • If currentlimit:
    • Raise StopIteration to stop the loop automatically.
question mark

Which of the following is required for an object to be considered iterable in Python?

Select the correct answer

Everything was clear?

How can we improve it?

Thanks for your feedback!

Section 5. Chapter 3

Ask AI

expand

Ask AI

ChatGPT

Ask anything or try one of the suggested questions to begin our chat

Section 5. Chapter 3
some-alt