Mixing for and next
You can even use next
inside a for
loop, but then you will have to handle the StopIteration
exception
that migh happen during your call of next
.
I am not really sure when would we want to use this.
from counter import Counter
cnt = Counter()
for i in cnt:
print(f"i: {i}")
try:
n = next(cnt)
print(f"n: {n}")
except Exception as ex:
print(ex.__class__.__name__)
break
Output:
i: 1
n: 2
i: 3
StopIteration