Python Iterators
Iterators in Python
An iterator in Python is an object that holds a sequence of values and provide
sequential traversal through a collection of items such as lists, tuples and
dictionaries. .
The Python iterators object is initialized using the iter() method.
It uses the next() method for iteration.
1. __iter__(): __iter__() method initializes and returns the iterator object itself.
2. __next__(): the __next__() method retrieves the next available item, throwing
a StopIteration exception when no more items are available.
Difference between Iterator and Iterable
Iterables are objects that can return an iterator. These include built-in data
structures like lists, dictionaries, and sets. Essentially, an iterable is anything
you can loop over using a for loop. An iterable implements the __iter__()
method, which is expected to return an iterator object.
Iterators are the objects that actually perform the iteration. They implement
two methods: __iter__() and __next__(). The __iter__() method returns the
iterator object itself, making iterators iterable as well.
iter()
s = "GFG"
it = iter(s)
print(next(it))
print(next(it))
print(next(it))
Creating an iterator
Creating a custom iterator in Python involves defining a class that
implements the __iter__() and __next__() methods according to the Python
iterator protocol.
Define the Class: Start by defining a class that will act as the iterator.
Initialize Attributes: In the __init__() method of the class, initialize any
required attributes that will be used throughout the iteration process.
Implement __iter__(): This method should return the iterator object itself.
This is usually as simple as returning self.
Implement __next__(): This method should provide the next item in the
sequence each time it’s called.
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))
StopIteration Exception
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.
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
You’re now expert about
Python Iterators