![]() |
VOOZH | about |
An iterator in Python is an object used to traverse through all the elements of a collection (like lists, tuples or dictionaries) one element at a time. It follows the iterator protocol, which involves two key methods:
Here are some key benefits:
Python provides built-in iterators for iterable objects such as strings, lists, tuples, and dictionaries. These iterators allow elements to be accessed one at a time using the next() function.
Example: Let’s start with a simple example using a string. We will convert it into an iterator and fetch characters one by one:
G F G
Explanation:
Creating a custom iterator in Python involves defining a class that implements the __iter__() and __next__() methods according to the Python iterator protocol.
Steps to follow:
Below is an example of a custom class called EvenNumbers, which iterates through even numbers starting from 2:
2 4 6 8 10
Explanation:
StopIteration exception is integrated with Python’s iterator protocol. It signals that the iterator has no more items to return. Once this exception is raised, further calls to next() on the same iterator will continue raising StopIteration.
Example:
100 200 300 End of iteration
In this example, the StopIteration exception is manually handled in the while loop, allowing for custom handling when the iterator is exhausted.
Although the terms iterator and iterable sound similar, they are not the same. An iterable is any object that can return an iterator, while an iterator is the actual object that performs iteration one element at a time.
Example: Let’s take a list (iterable) and create an iterator from it
1 2 3
Explanation:
To make the difference even clearer, let’s summarize it in a simple table:
| Feature | Iterable | Iterator |
|---|---|---|
| Definition | Any object that can return an iterator | Object with a state for iteration |
| Key Method | Implements __iter__() | Implements both __iter__() and __next__() |
| Examples | List, Tuple, String, Dictionary, Set | Objects returned by iter() |
Can use next() directly? | No | Yes |