This Stack Overflow post is about making an object an iterator in Python.
In Python 2, that means you need to implement an __iter__()
method, and a next()
method. But in Python 3, you need to implement a different method, instead of next()
you need to implement __next__()
.
How does one make an object which is an iterator in both Python 2 and 3?
The __iter__() function returns an iterator for the given object (array, set, tuple, etc. or custom objects). It creates an object that can be accessed one element at a time using __next__() function, which generally comes in handy when dealing with loops.
To create an object/class as an iterator you have to implement the methods __iter__() and __next__() to your object. As you have learned in the Python Classes/Objects chapter, all classes have a function called __init__() , which allows you to do some initializing when the object is being created.
Technically speaking, a Python iterator object must implement two special methods, __iter__() and __next__() , collectively called the iterator protocol. An object is called iterable if we can get an iterator from it.
Iterable is an object, which one can iterate over. It generates an Iterator when passed to the iter() method. Lists, tuples, dictionaries, strings and sets are all iterable objects. They are iterable containers that you can convert into an iterator.
Just give it both __next__
and next
method; one can be an alias of the other:
class Iterator(object):
def __iter__(self):
return self
def __next__(self):
# Python 3
return 'a value'
next = __next__ # Python 2
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With