An iterator is an item that contains a countable number of qualities.
An iterator is an item that can be iterated after, implying that you can navigate through every one of the qualities.
Technically, in Python, an iterator is an object which implements the iterator protocol, which consist of the methods __iter__() and __next__().
Iterator versus Iterable
Records, tuples, word references, and sets are for the most part iterable items. They are iterable holders that you can get an iterator from.
Every one of these items has an iter() technique which is utilized to get an iterator:
Example
Return an iterator from a tuple, and print each value:
mytuple = (“apple”, “banana”, “cherry”)
myit = iter(mytuple)
print(next(myit))
print(next(myit))
print(next(myit))
Even strings are iterable objects, and can return an iterator:
Example
Strings are also iterable objects, containing a sequence of characters:
mystr = “banana”
myit = iter(mystr)
print(next(myit))
print(next(myit))
print(next(myit))
print(next(myit))
print(next(myit))
print(next(myit))
Looping Through an Iterator
We can also use a for loop to iterate through an iterable object:
Example
Iterate the values of a tuple:
mytuple = (“apple”, “banana”, “cherry”)
for x in mytuple:
print(x)
Make an Iterator
To make an item/class as an iterator you need to execute the techniques __iter__() and __next__() to your article.
As you have learned in the Python Classes/Items part, all classes have a capacity called __init__(), which permits you to do some introducing when the article is being made.
The __iter__() technique acts comparable, you can do tasks (instating and so on.), yet should consistently restore the iterator object itself.
The __next__() technique additionally enables you to do activities, and must restore the following thing in the grouping.
Example
Create an iterator that returns numbers, starting with 1, and each sequence will increase by one (returning 1,2,3,4,5 etc.):
class MyNumbers:
def __iter__(self):
self.a = 1
return self
def __next__(self):
x = self.a
self.a += 1
return x
myclass = MyNumbers()
myiter = iter(myclass)
print(next(myiter))
print(next(myiter))
print(next(myiter))
print(next(myiter))
print(next(myiter))
StopIteration
The model above would proceed always in the event that you had enough straightaway() proclamations, or in the event that it was utilized in a for circle.
To forestall the emphasis to go on perpetually, we can utilize the StopIteration explanation.
In the __next__() method, we can add a terminating condition to raise an error if the iteration is done a specified number of times:
Example
Stop after 20 iterations:
class MyNumbers:
def __iter__(self):
self.a = 1
return self
def __next__(self):
if self.a <= 20:
x = self.a
self.a += 1
return x
else:
raise StopIteration
myclass = MyNumbers()
myiter = iter(myclass)
for x in myiter:
print(x)