Python Iterator
- Previous Page Python Inheritance
- Next Page Python Scope
Python Iterator
An iterator is an object that contains a countable number of values.
An iterator is an iterable object, which means you can traverse all values.
Technically, in Python, an iterator is an object that implements the iterator protocol, which contains methods __iter__()
and __next__()
.
Iterator VS Iterable Object
lists, tuples, dictionaries, and sets are iterable objects. They are iterable containers from which you can obtain iterators (Iterators).
All these objects have methods to get iterators iter()
Method:
Instance
Return an iterator from the 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:
Instance
Strings are also iterable 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)) print(next(myit))
Traverse the iterator
We can also use a for loop to traverse iterable objects:
Instance
Iterate over the values of the tuple:
mytuple = ("apple", "banana", "cherry") for x in mytuple: print(x)
Instance
Iterate over the characters in the string:
mystr = "banana" for x in mystr: print(x)
Tip:The for loop actually creates an iterator object and performs next()
method.
to create an iterator
To create an object/class as an iterator, you must implement __iter__()
and __next__()
method.
As you learned in the Python class/object chapter, all classes have a method named __init__()
A function that allows you to perform some initialization when creating an object.
__iter__()
The method serves a similar purpose, you can perform operations (initialization, etc.), but you must always return the iterator object itself.
__next__()
The method also allows you to perform operations and must return the next item in the sequence.
Instance
Create an iterator that returns numbers, starting from 1, and each sequence will increase by 1 (return 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
If you have enough next()
statement, or use it in a for loop, then the above example will go on forever.
To prevent the iteration from going on forever, we can use StopIteration
statement.
in __next__()
In a method, if the iteration completes the specified number of times, we can add a termination condition to raise an error:
Instance
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)
- Previous Page Python Inheritance
- Next Page Python Scope