Previous lesson: Python classes and objects List, tuple, dict, and sets are all iterable objects. They are iterable containers from which you can get an iterator. All of these objects have an iter()
method, which is used to get the iterator. Let’s get an iterator from a tuple and output each value:
mytuple = ("apple", "banana", "cherry")
myit = iter(mytuple)
print(next(myit))
print(next(myit))
print(next(myit))
Output:
apple
banana
cherry
Even strings are iterated objects and can return an iterator.
mystr = "banana"
myit = iter(mystr)
print(next(myit))
print(next(myit))
print(next(myit))
print(next(myit))
print(next(myit))
Conclusion:
б
а
н
а
н
Table of Contents
A loop through an iterator
We can also use the for
loop to iterate over an iterated object.
mytuple = ("apple", "banana", "cherry")
for x in mytuple:
print(x)
Output:
apple
banana
cherry
Iterate the characters of the string:
mystr = "banana"
for x in mystr:
print(x)
Conclusion:
б
а
н
а
н
The for
loop actually creates an iterator object and executes the next()
method for each loop.
Creating an iterator
To create an object/class as an iterator, you need to implement __iter__()
and __next__()
methods for the object. As you learned in the Python Classes and Objects lesson , all classes have a function called __init__()
that allows you to do an initialization when you create an object. The __iter__()
method acts similarly, you can do operations (initialization, etc.) but you should always return the iterator object itself. The __next __()
method also allows you to perform operations and must return the next element in the sequence. Create an iterator that returns numbers starting with 1 and incremented 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))
Output:
1
2
3
4
5
StopIteration
The above example will iterate forever as long as you call the next()
operator or if you use it in a for
loop. To avoid iterating forever, we can use the StopIteration
operator. In the __next __()
method we can add an end condition to cause an error if the iteration iterates a specified number of times:
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)
Output:
1
2
3
...
18
19
20