Keyboard shortcuts

Press or to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

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