Base de conhecimentoCentro de Exames
PT · PTPortuguês (Portugal)
Escolher idioma13

CKTIS / Python

iterator.__next__

O método do iterador devolve o elemento seguinte e lança StopIteration ao esgotar-se.

Versão: Python 3.14; repository image, production runtime not attested

Sintaxe

item = next(iterator)

O método do iterador devolve o elemento seguinte e lança StopIteration ao esgotar-se.

iterator.__next__

next(it) usa o protocolo e next(it, default) devolve o valor indicado no fim. None pode ser um elemento normal. Um iterador correto permanece esgotado.

A primeira chamada dá 1, list consome o restante [0] e a última dá end.

it=iter([None])
assert next(it) is None
for _ in range(2):
    try: next(it)
    except StopIteration: pass
    else: raise AssertionError

Exemplos

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

it = Countdown(2)
print(next(it), list(it), next(it, "end"))

Resultado

1 [0] end

A primeira chamada dá 1, list consome o restante [0] e a última dá end.

Fontes