← Python lessons

Python Iterators: iter(), next() and How for Loops Work

A Python iterator gives you one item at a time. Use iter() to get an iterator and next() to ask for its next item.

Get an iterator with iter()

An iterable, such as a list, can supply an iterator. The iterator remembers your position.

names = ["Ada", "Bo", "Cy"]
iterator = iter(names)
print(next(iterator))
print(next(iterator))

The calls print Ada, then Bo.

Handle the end with next()

An exhausted iterator raises StopIteration. Give next() a default to return instead.

iterator = iter([10])
print(next(iterator))
print(next(iterator, "finished"))
print(next(iterator, "finished"))

After 10, both calls print finished. An exhausted iterator stays exhausted.

How a for loop uses an iterator

A for loop gets an iterator, then requests items until StopIteration. This loop shows those steps explicitly.

iterator = iter([2, 4, 6])
while True:
    try:
        number = next(iterator)
    except StopIteration:
        break
    print(number)

This prints the same values as for number in [2, 4, 6]: print(number).

Continue from the current position

Calling iter() on an iterator returns that same iterator. A list can supply a fresh iterator each time.

numbers = [2, 4, 6]
iterator = iter(numbers)
print(next(iterator))
print(list(iterator))
print(list(iterator))
print(list(numbers))

The iterator supplies 2, then [4, 6], then []. The original list still contains every value.

See also: For loops, Generators and yield.

Your turn

Create an iterator from scores, then print its first two items separately.

scores = [12, 18, 25]
# add three lines: create an iterator, then print next() twice

Expected output

12
18

Practise this in the free Python course, where every exercise checks your code instantly.