Python how to make an iterator

Python: Create an Iterator with Examples. Learn how to create an iterator in Python, with examples of iterating over lists, tuples, and dictionaries.

Creating Iterators in Python

An iterator is an object that can be iterated upon, meaning that it will return data, one element at a time. In Python, an iterator is an object that implements the iterator protocol, which consists of the methods __iter__() and __next__().

The __iter__() method is called when the iterator object is initialized. It returns an iterator object that defines the __next__() method that accesses elements in the container one at a time. For example, let's consider a list:


my_list = [1, 2, 3, 4]

We can create an iterator object from this list using the iter() function, like this:


my_iter = iter(my_list)

The __next__() method can then be called to access elements in the list, one at a time. Let's call __next__() twice to get the first two elements:


print(next(my_iter))  # prints 1
print(next(my_iter))  # prints 2

Once all the elements have been iterated over, a StopIteration error is raised. So, if we call __next__() again, we will get a StopIteration error:


print(next(my_iter))  # raises StopIteration

We can also use a for loop to iterate over the elements of the list, like this:


for element in my_list:
    print(element)

This for loop is equivalent to manually calling the __next__() method on the iterator object, like this:


my_iter = iter(my_list)

while True:
    try:
        element = next(my_iter)
        print(element)
    except StopIteration:
        # iteration has stopped
        break

We can also create our own iterator objects. To do this, we need to implement the two methods of the iterator protocol: __iter__() and __next__().

The __iter__() method should return the iterator object itself. For example:


class MyIterator:

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

The __next__() method should return the next element of the container. For example:


def __next__(self):
    if self.num <= 10:
        val = self.num
        self.num += 1
        return val
    else:
        raise StopIteration

We can then create an instance of our iterator class and use it to iterate over the numbers from 1 to 10:


my_iter = MyIterator()
for num in my_iter:
    print(num)

This will print out the numbers from 1 to 10.

In conclusion, an iterator is an object that implements the iterator protocol, which consists of the methods __iter__() and __next__(). We can create iterator objects from existing containers, such as lists, or we can create our own iterator objects by implementing the iterator protocol. Iterators allow us to access elements of a container one at a time.

Answers (0)