Iteration
Iterators
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
GraceA 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
GuidoThe 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
AdaNotes
- Iterables produce iterators; iterators produce values.
next()consumes one value from an iterator.- Many iterators are one-pass even when the original collection is reusable.
See also
- related: Iterating over Iterables
- related: Iterator vs Iterable
- related: Generators
Run the complete example
Expected output
Ada
Grace
Guido
Ada
Execution time appears here after you run the example.