Python3 Iterators and Builders
iterator
Iteration is one of Python's most powerful features and a way to access collection elements.
An iterator is an object that remembers the location of the traversal.
The iterator object is accessed from the first element of the collection until all elements have been accessed. The iterator can only go backwards without going forward.
There are two basic methods for iterators: iter() and next().
Strings, lists, or tuple objects can be used to create iterators:
Instance (Python 3.0+)
Iterator objects can be traversed using the regular for statement:
Instance (Python 3.0+)
Execute the above program, the output is as follows:
1 2 3 4
Can also be used next() function:
Instance(Python 3.0+)
You can also use the next() function:
Instance(Python 3.0+)
Execute the above program, the output is as follows:
1 2 3 4
Create an iterator
Using a class as an iterator requires implementing two methods __iter__() and __next__() in the class.
If you already know about object-oriented programming, you know that classes have a constructor, and Python's constructor is __init__(), which is executed when the object is initialized.
The__iter__() method returns a special iterator object that implements the __next__() method and identifies the completion of the iteration through the StopIteration exception.
The__next__() method (next() in Python 2) returns the next iterator object.
Create an iterator that returns a number with an initial value of 1 and incrementing by 1:
Instance(Python 3.0+)
Execution output is:
1 2 3 4 5
StopIteration
The StopIteration exception is used to identify the completion of an iteration to prevent an infinite loop. In the __next__() method we can set the StopIteration exception to be fired after the specified number of loops has been completed.
Stop execution after 20 iterations:
Instance(Python 3.0+)
Execution output is:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
Builder
In Python, a function that uses yield is called a generator.
Unlike normal functions, the generator is a function that returns an iterator. It can only be used for iterative operations. It is easier to understand that the generator is an iterator.
When the call generator runs, the function pauses and saves all current run information each time it encounters yield, returns the value of yield, and continues to run from the current position the next time the next() method is executed.
Invoke a generator function that returns an iterator object.
The following example uses yield to implement the Fibonacci sequence:
Instance(Python 3.0+)
Execute the above program, the output is as follows:
0 1 1 2 3 5 8 13 21 34 55