Story – Python Iterators

Alex had learned a lot about object-oriented programming and how it could make his code more efficient and easier to maintain. He wanted to continue to expand his knowledge, so he began to study Python iterators.

An iterator is an object that can be iterated (looped) upon. Alex found that Python has several built-in objects that are iterators, such as lists, tuples, and dictionaries. He also discovered that he could create his own iterators using the iter() and next() functions.

To demonstrate this concept, Alex created a simple list of fruits and used a for loop to iterate over each item in the list.

fruits = ["apple", "banana", "cherry"]

for fruit in fruits:
    print(fruit)

The output was:

apple
banana
cherry

Next, Alex used the iter() function to create an iterator for the same list of fruits.

fruits = ["apple", "banana", "cherry"]
fruit_iterator = iter(fruits)

print(next(fruit_iterator))
print(next(fruit_iterator))
print(next(fruit_iterator))

The output was:

apple
banana
cherry

Alex was able to see that by creating an iterator object, he could use the next() function to iterate over the elements of the list one by one.

To create his own iterator class, Alex defined a class that included the __iter__() and __next__() methods. The __iter__() method returned the iterator object itself, while the __next__() method returned the next value in the iteration.

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

    def __iter__(self):
        return self

    def __next__(self):
        if self.current_val < self.max_val:
            self.current_val += 1
            return self.current_val
        else:
            raise StopIteration

my_iterator = MyIterator(3)

print(next(my_iterator))
print(next(my_iterator))
print(next(my_iterator))

The output was:

1
2
3

Alex was excited to see how easy it was to create his own iterator class and use it to iterate over a set of values.

He continued to experiment with iterators, exploring different ways to create and use them in his Python code. He found that iterators were a powerful tool that could simplify complex code and make it more readable and maintainable.