An iterator can traverse sequence objects such as lists, dictionaries, and strings, and even custom objects. Its essence is to record the position of each element in the iterated object. The iterative process starts from the first element to the last element, and the process cannot be rolled back or iterated in the opposite direction.
Two basic methods iter, next
Sequence objects can directly create iterators using iter() and iterate over the iterators through next().
Iterate with for loop
S = 'PYTHON' IT = iter(S) for it in IT: print(it)
Example results:
P
Y
T
H
O
N
Iterate with next()
S = 'PYTHON' IT = iter(S) print(next(IT)) print(next(IT)) print(next(IT)) print(next(IT)) print(next(IT)) print(next(IT))
Example results:
P
Y
T
H
O
N
When we iterate with next(), if the number of iterations exceeds the number of elements in the iterator, StopIteration will be triggered. Therefore, we can use the while loop to iterate and continuously capture the exceptions ending in the iteration to complete the iteration process of the for loop.
S = 'PYTHON' IT = iter(S) while True: try: print(next(IT)) except StopIteration: break
P
Y
T
H
O
N
Manually build the iterator
Using a class as an iterator requires implementing two methods in the class iter () and next () . The iter () method returns a special iterator object that implements the next () method and identifies the completion of iteration through the StopIteration exception. The next () method (next() in Python 2) returns the next iterator object. The following class constructs an iterator to accept an iterable number, and each iteration returns the square of the result of the last iteration, and an exception is thrown when the result of the iteration is greater than 9999999999999999999999. Use this class to create an example to iterate the square sum of the number 2.
class IT_SQUARE: def __init__(self, x): = x def __next__(self): = ** 2 if > 9999999999999: raise StopIteration else: return def __iter__(self): return self IT1 = IT_SQUARE(2) while True: try: print(IT1.__next__()) except StopIteration: break
Sample results
4
16
256
65536
4294967296
Summarize
The above is the example code for manually creating iterators in Python 3 introduced to you. I hope it will be helpful to you. If you have any questions, please leave me a message and the editor will reply to you in time. Thank you very much for your support for my website!
If you think this article is helpful to you, please reprint it. Please indicate the source, thank you!