Iterators in Python (original) (raw)
Last Updated : 16 Dec, 2024
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.
- **__iter__(): __iter__() method initializes and returns the iterator object itself.
- **__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.
Python iter() Example
Python `
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.
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:
- **Initialization: The __iter__() method initializes the iterator at 2, the first even number.
- **Iteration: The __next__() method retrieves the current number and then increases it by 2, ensuring the next call returns the subsequent even number.
- **Usage: We create an instance of EvenNumbers, turn it into an iterator and then use the next() function to fetch even numbers one at a time.
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.
**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
`
Output
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.