Introduction to Python Iterators

python_tutorials

What are Iterators?

An iterator in Python refers to an object that we can iterate upon. The iterator consists of countable values, and it is possible to traverse through these values, one by one.

The iterator simply implements the Python’s iterator protocol. The iterator protocol is a Python class which comes with two special methods, namely __iter__() and __next__(). With these two methods, the iterator is able to compute the next value in the iteration.

With iterators, it is easy for us to work with sequences of items in Python. We don’t have to allocate computing resources to all the items in the sequence, rather we iterate upon single item at a time which helps us save the memory space.

In this article, we will study how to work with iterators in Python.

Iterable Objects in Python

An iterable is an object capable of returning an iterator. An iterable can represent both finite and infinite data sources. The iterable directly or indirectly implements the two methods: __iter__() and __next__(). The __iter__() method returns the iterator object while the __next__() method helps us traverse the elements in the iterable object.

Examples of iterable objects in Python include Lists,

To finish reading, please visit source site