×

python · level 3 · unit 1 · lesson 3

  1. meet it
  2. guess first
  3. your turn
  4. fix it
  5. nailed it

Tap a green word if you get lost.

meet it

A for loop asks an for one item at a time.

Lists, strings, dictionaries and files are all : you can loop over them. Behind every for loop, Python calls iter() on the iterable to get an iterator, a little helper that remembers where it got to.

Then it calls next() on the iterator again and again, and each call hands out one item. When nothing is left, the iterator raises , and the loop stops quietly.

An iterator only goes forwards, and only once. A list can be looped over many times, because each new loop asks it for a fresh iterator.

queue = ["Ana", "Ben", "Cara"]
helper = iter(queue)
print(next(helper))
print(next(helper))
for name in helper:
    print("Still waiting:", name)

A file opened with with open is its own iterator, which is why reading it twice gives nothing the second time.