Python Iterators – Tutorial with Examples

Iterators are a crucial concept in Python and are used extensively in many areas of the language. In this article, you will learn about iterators in Python, how to create them, and how to use them in your own programs.

What are Iterators?

Iterators are objects that can be iterated (looped) upon. An object which returns data, one element at a time when iterated is called an iterator. In Python, an iterator must implement two special methods, __iter__() and __next__(), collectively called the iterator protocol. The __iter__() method returns the iterator object itself and the __next__() method returns the next item from the iterator.

In Python, many built-in data types are iterable. For example, lists, tuples, and strings are iterable data types. You can loop over these data types using a for loop and access each element one by one. However, you can also create your own iterable objects by implementing the iterator protocol in your classes.

Creating an Iterator

To create an iterator in Python, you need to implement the iterator protocol in your class. To do this, you need to define the __iter__() and __next__() methods in your class.

Here is an example of a simple iterator that returns the numbers 0 to 4:

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

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

In this example, the __iter__() method returns the iterator object itself, which is the instance of the class. The __next__() method returns the next item from the iterator. In this case, it returns the next number in the sequence starting from 0. If all the items have been returned, the method raises the StopIteration exception to signal that there are no more items to be returned.

You can use this iterator in a for loop like this:

for i in MyIterator():
    print(i)

This will print the numbers 0 to 4, one number per line.

Using Iterators in Python

Iterators are used in many different ways in Python. For example, you can use them in for loops, with the built-in next() function, or with the iter() function. In this section, you will learn how to use iterators in each of these ways.

Using Iterators in For Loops

You can use iterators in for loops to loop over the elements in an iterator. For example, you can use the MyIterator class from the previous section in a for loop like this:

for i in MyIterator():
    print(i)

This will print the numbers 0 to 4, one number per line.

Using the Built-in next() Function

You can also use the built-in next() function to get the next item from an iterator. For example, you can use it with the MyIterator class from the previous section like this:

my_iterator = MyIterator()
print(next(my_iterator))
print(next(my_iterator))
print(next(my_iterator))
print(next(my_iterator))
print(next(my_iterator))

This will print the numbers 0 to 4, one number per line.

Using the Built-in iter() Function

You can also use the built-in iter() function to create an iterator from an iterable object. For example, you can use it with a list like this:

my_list = [0, 1, 2, 3, 4]
my_iterator = iter(my_list)
print(next(my_iterator))
print(next(my_iterator))
print(next(my_iterator))
print(next(my_iterator))
print(next(my_iterator))

This will print the numbers 0 to 4, one number per line.

Conclusion

Iterators are a crucial concept in Python and are used extensively in many areas of the language. In this article, you learned about iterators in Python, how to create them, and how to use them in your own programs. You also learned about the iterator protocol and how to use the built-in next() and iter() functions with iterators.

Now that you have a solid understanding of iterators in Python, you can use them in your own programs to write efficient and readable code.

Leave a Reply

Your email address will not be published. Required fields are marked *