Solution:
When using next()
to access an iterator that has been iterated, there will be such an error: stopiteration
the solution is to give a default value: next (ITER, default)
, which will be output after the iteration is completed
suppose that the original writing method of the loop is:
a = next(iter_test) # Iteration completion will report an error StopIteration
print(a)
Change to:
a = next(iter_test,None)
if a is not None:
print(a)
Problem analysis
The following code will report an error:
iter_list = iter([1, 2, 3, 4])
for i in range(10):
print(next(iter_list))
Error will be reported after outputting 1234, which can be changed to:
iter_list = iter([1, 2, 3, 4])
for i in range(10):
a = next(iter_list, None)
if a is not None:
print(a)
This will output: 1 2 3 4