Iteration

Iterators

iter and next expose the protocol behind for loops.

iter() asks an iterable for an iterator. next() consumes one value and advances the iterator's position.

Source

names = ["Ada", "Grace", "Guido"]
iterator = iter(names)
print(next(iterator))
print(next(iterator))

Output

Ada
Grace
ITERABLE[a,b,c]iter()ITERATORnext()abc
iter() exposes the iterator behind for; next() pulls one value at a time until exhausted.

A for loop consumes the same iterator protocol. Because two values were already consumed, the loop sees only the remaining value.

Source

for name in iterator:
    print(name)

Output

Guido

The list itself is reusable. Asking it for a fresh iterator starts a new pass over the same stored values.

Source

again = iter(names)
print(next(again))

Output

Ada

Notes

See also

Run the complete example

Example code

Expected output

Ada
Grace
Guido
Ada

Execution time appears here after you run the example.