Special Method Protocols

__next__() — containers protocol

Supply the next item of an iterator. Raise StopIteration when exhausted and continue to raise it on subsequent calls. Return values, including None, are valid elements and do not indicate exhaustion.

Formal Syntax & Structure

python syntaxpython
def __next__(self):

Return Value

object

Next element, or StopIteration at exhaustion.

Working Example

Example Snippetpython
class Countdown:    def __init__(self,n): self.n=n    def __iter__(self): return self    def __next__(self):        if self.n<=0: raise StopIteration        self.n-=1        return self.n+1print(list(Countdown(3)))
Python Reference