Itterators
What is an iterator in Python?
An iterator is a python object which has n number of elements on which we can traverse one by one.
Iterator and Iterable
Iterator is an object, which one can iterate over. It generates an Iterator when passed to the iter() method.
eg, List, tuples, dictionaries, strings and sets are all iterable objects.
Note that every iterator is also an iterable, but not every iterable is an iterator.
Which methods are defined in an iterator class in Python?
__iter()__
__next()__
__iter()__
This method returns the iterator object itself as mentioned above.
eg,
list1 = [0, 1, 2]
iter1 = list1.__iter__()
#This will convert an iterable to iterator.
print(iter1.__next__())
Create an Iterator
Till now we have only used the inbuilt iterables such as lists or strings, but we can also build an iterator from scratch is easy in Python. We just have to implement the __iter__() and the __next__() methods.
Here is our own custom Iterator that returns an even number or 1 every time we iterate upon it:
class Evenit:
def __init__(self, max=0):
self.max = max
def __iter__(self):
self.n = 0
return self
def __next__(self):
if self.n <= self.max:
if self.n % 2 ==0:
result=self.n
self.n += 1
return result
else:
self.n += 1
return 1
else:
raise StopIteration
# create an object
numbers = Evenit(10)
for i in numbers:
print(i)
Output:
0
1
2
1
4
1
6
1
8
1
10
As we can see, this iterator returns even numbers up to 10 (because we have given the argument to the event as 10), and whenever it encounters an odd number, it just returns 1. In a similar manner, you can create your own iterator.
This brings us to the end of this article where we learned about iterators in Python and also created our own custom iterator from scratch.