🎓 A1Learner
🔍

Python Iterators

An iterator is an object that hands out items one at a time. A for loop uses an iterator to walk an iterable.

Make an iterator

iter() turns a list into an iterator. next() then takes the first item.

colours = ["red", "green", "blue"]
it = iter(colours)
print(next(it))

Take one item at a time

Each next() call moves forward one step. Nothing repeats and nothing is skipped.

colours = ["red", "green", "blue"]
it = iter(colours)
print(next(it))
print(next(it))
print(next(it))

Strings and tuples work too

A string gives its letters one at a time. A tuple gives its items in order.

word_it = iter("hi")
print(next(word_it))
print(next(word_it))
pair_it = iter((10, 20))
print(next(pair_it))

What a for loop does

This loop prints the same three colours. Behind the scenes, Python uses iter() and next().

colours = ["red", "green", "blue"]
for colour in colours:
    print(colour)

One step too far

The list has only one item. The second next() call raises StopIteration.

it = iter(["red"])
print(next(it))
print(next(it))

Example

colours = ("red", "green", "blue")
it = iter(colours)
print(next(it))
print(next(it))
print(next(it))

Key points

  • Iterable: a value you can walk through, one item at a time
  • Iterator: an object that hands out items one at a time
  • Use iter() to make an iterator from an iterable
  • Use next() to take the next item from an iterator
  • StopIteration: the error that says an iterator has no items left

In this example, colours is a tuple with three items. iter(colours) makes an iterator and stores it in it. Each print(next(it)) takes the next colour. The first call prints red, and the second prints green. The third call prints blue. The code stops after three calls, so no error appears.

Note

A for loop uses iter() and next() for you behind the scenes.

Try it Yourself

Edit the code, then press Run.

Running is simulated · Python Playground

Exercise

What does next(it) do?