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.

  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.

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.

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:

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.