Python Iterators

In the realm of Python, understanding the distinction between ‘iterators’ and ‘iterables’ is foundational. An iterable is an object that can return an iterator, such as lists, tuples, and strings. In contrast, an iterator is the object that actually does the work: it traverses through an iterable, one element at a time.

To put it simply, an iterable is like a book with pages, while an iterator is like the process of turning each page.

Example:

my_list = [1, 2, 3]  # Iterable
my_iter = iter(my_list)  # Iterator

Looping Through an Iterator: A Practical Approach

The real power of iterators comes into play when we loop through them. Using a for loop, Python automatically fetches the iterator from the iterable and makes the process seamless.

Example:

for element in my_list:  # Looping directly through the iterable
    print(element)

Creating Your Own Iterator: A Step-by-Step Guide

Creating your own iterator in Python is both insightful and rewarding. This is achieved by defining a class with __iter__() and __next__() methods.

Example:

class MyIterator:
    def __init__(self, max_val):
        self.max = max_val

    def __iter__(self):
        self.num = 0
        return self

    def __next__(self):
        if self.num >= self.max:
            raise StopIteration
        self.num += 1
        return self.num

Handling the StopIteration: The End of the Journey

StopIteration is an integral part of iterators. It signals the end of the iteration process. When an iterator has no more values to return, it raises a StopIteration exception, signaling the loop to end.

Example:

my_iterator = MyIterator(3)
for number in my_iterator:
    print(number)

In this code, the StopIteration is raised internally when the iterator reaches the specified limit.