Python has two main constructs iterator and iterables Iteration protocol. The Iterable object implements __iter__()
method and returns an Iterator object. The Iterator object implements the __next__()
method and raises a StopIteration
when the elements of the iterable object are exhausted.
The Iterator object is itself an Iterable as it must also implement the __iter__()
method and simply return itself.
To make your class Iterable we need to override __iter__() function inside our class i.e.
def __iter__(self):
pass
To create an Iterator class we need to override the next() function inside our class i.e.
def __next__(self):
pass
Make class iterable Python example
Simple example code implements and uses Iterables and Iterators.
class Counter:
def __init__(self, low, high):
self.current = low - 1
self.high = high
def __iter__(self):
return self
def __next__(self): # Python 2: def next(self)
self.current += 1
if self.current < self.high:
return self.current
raise StopIteration
for c in Counter(1, 5):
print(c)
Output:
- The
__iter__
returns the iterator object and is implicitly called at the start of loops. - The
__next__()
method returns the next value and is implicitly called at each loop increment. This method raises a StopIteration exception when there is no more value to return, which is implicitly captured by looping constructs to stop iterating.
Why should we make a Custom class Iterable?
Answer: Custom classes created by us are by default, not Iterable. If we want to iterate over the objects of our custom class then we need to make them Iterable and also create an Iterator class for them.
Do comment if you have any doubts or suggestions on this Python iterable topic.
Note: IDE: PyCharm 2021.3.3 (Community Edition)
Windows 10
Python 3.10.1
All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.