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

The Iterator Protocol

Scorri per mostrare il 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)

__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?

Seleziona la risposta corretta

Tutto è chiaro?

Come possiamo migliorarlo?

Grazie per i tuoi commenti!

Sezione 5. Capitolo 3

Chieda ad AI

expand

Chieda ad AI

ChatGPT

Chieda pure quello che desidera o provi una delle domande suggerite per iniziare la nostra conversazione

Sezione 5. Capitolo 3
some-alt