Iterators in Python
Learn how to build an iterator.
We'll cover the following
In the previous lesson, we pondered over the decency of the for
loop. Now let’s unveil it and see the magic behind it.
What is an iterator?
In Python, an iterator is an object that implements the __iter__
and __next__
dunder methods.
⚙️ Note: Dunder methods are methods having two prefix and suffix underscores in the method name. They are also known as magic methods. For example:
__init__
,__len__
,__repr__
, etc.
The __iter__()
function returns an iterator object that goes through each element of the given object. Whereas, the __next__()
function returns the next item in the sequence.
Objects that support the __iter__
and __next__
methods automatically work with loops.
Iterator from scratch
To create an iterator class, it must implement the __iter__()
and __next()
methods. Let’s create an iterator that returns numbers.
Create a free account to view this lesson.
By signing up, you agree to Educative's Terms of Service and Privacy Policy