Last Updated : 11 Aug, 2025
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:
s = "GFG"
it = iter(s)
print(next(it))
print(next(it))
print(next(it))
Creating an Custom Iterator
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:
Python
class EvenNumbers:
def __iter__(self):
self.n = 2 # Start from the first even number
return self
def __next__(self):
x = self.n
self.n += 2 # Increment by 2 to get the next even number
return x
# Create an instance of EvenNumbers
even = EvenNumbers()
it = iter(even)
# Print the first five even numbers
print(next(it))
print(next(it))
print(next(it))
print(next(it))
print(next(it))
Explanation:
The 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:
Python
li = [100, 200, 300]
it = iter(li)
# Iterate until StopIteration is raised
while True:
try:
print(next(it))
except StopIteration:
print("End of iteration")
break
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.
Difference between Iterator and Iterable 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()RetroSearch is an open source project built by @garambo | Open a GitHub Issue
Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo
HTML:
3.2
| Encoding:
UTF-8
| Version:
0.7.4