We will try to learn how to create and use iterators and how to write our own objects as iterable. Let’s first try to understand what iterators are
What are Iterators?
Iterators are actually used in Python even though we don’t see them in most places. Iterators are especially encountered in for loops, list comprehensions, and generators that we will see in the next lesson. Iterators are an object that can be navigated in the most general sense, and this object returns one element at a time. In Python, every object that we can create an iterator from is an iterable object. In order for an object to be iterable, it must define the ready methods iter () __ and __next () .
Creating Iterator
To create an iterator object from an iterable object (list, bundle, string, etc.), we use the push () function in Python and use the next () function to get the next element of that object.
myList = [1,2,3,4,5]
print(dir(myList))
['__add__', '__class__', '__contains__', '__delattr__', '__delitem__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__gt__', '__hash__', '__iadd__', '__imul__', '__init__', '__init_subclass__', '__iter__', '__le__', '__len__', '__lt__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__reversed__', '__rmul__', '__setattr__', '__setitem__', '__sizeof__', '__str__', '__subclasshook__', 'append', 'clear', 'copy', 'count', 'extend', 'index', 'insert', 'pop', 'remove', 'reverse', 'sort']
iterator = iter(myList)
print(next(iterator))
print(next(iterator))
print(next(iterator))
print(next(iterator))
print(next(iterator))
1 2 3 4 5
print(next(iterator))
StopIteration Traceback (most recent call last) <ipython-input-3-d4aa693aba62> in <module> ----> 1 print(next(iterator)) StopIteration:
Here we can create an iterator from an iterable object, and get the next element of the object with the next () function. But when there are no more elements, we get the StopIteration error. This is the use of iterators. In fact, although we don’t notice, for loops in Python actually use iterators when hovering over an object.
myList = [1,2,3,4,5]
for i in myList:
print(i)
1 2 3 4 5
In fact, the internal structure of for loops is as follows;
myList = [1,2,3,4,5]
iterator = iter(myList)
while True:
try:
print(next(iterator))
except StopIteration:
break
1 2 3 4 5
Creating Our Own Iterable Objects
So how do we make iterable for the datas that we create? For this, the classes that we will create must define the iter () __ and __next () methods. Now let’s create a control class and make iterable.
class Command():
def __init__(self,chanels):
self.chanels = chanels
self.index = -1
def __iter__(self):
return self
def __next__(self):
self.index += 1
if (self.index < len(self.chanels)):
return self.chanels[self.index]
else:
self.index = -1
raise StopIteration
command = Command(['A chanel','B chanel','C chanel','D chanel'])
iterator = iter(command)
print(next(iterator))
print(next(iterator))
print(next(iterator))
print(next(iterator))
A chanel B chanel C chanel D chanel
Leave a comment