Python 3D Academyবাংলা

Iterators: one item at a time

🌍 In real life. At a bank, a token machine gives out queue numbers. Press the button: token 1. Press again: token 2. The machine remembers where it is, and when the roll of tokens runs out, it can't give any more.

Python has the same idea. A list, a string or a range is an iterable: something you can go through. To actually go through it, Python makes an iterator, a little token machine:

  • iter(something) makes the iterator
  • next(it) presses the button: you get the next item
  • when nothing is left, next raises StopIteration

The idea in one sentence: an iterable is something you can go through, and iter() gives you an iterator that hands out its items one at a time with next(), raising StopIteration when there are none left.

Its words:

  • iterable: a list, string, range, dict, file: anything a for loop accepts
  • iterator: the "token machine" that remembers where it is
  • next(it): give me the next item
  • StopIteration: the signal that the iterator is used up
tokens = iter(["A1", "A2", "A3"])
print(next(tokens))
print(next(tokens))
print(next(tokens))
print(next(tokens, "no more tokens"))
next(it, default) gives the default instead of raising StopIteration when nothing is left.

Why it matters: this is exactly what every for loop does for you, step by step:

  1. for x in items: first calls iter(items)
  2. each round, it calls next(...) and puts the item in x
  3. when next raises StopIteration, the loop stops quietly

An iterator is used up as it goes: once an item is handed out, that iterator won't give it again. A list can be looped over many times, because each for makes a fresh iterator.

queue = ["Ana", "Bo", "Cy"]
it = iter(queue)
print("first:", next(it))
for name in it:          # carries on from where next() left off
    print("then:", name)
print(list(it))          # used up: nothing left
print(list(queue))       # the list itself is untouched

Mistakes and edge cases.

  • next() on a list. next([1, 2]) gives TypeError: 'list' object is not an iterator: a list is iterable, but you need iter(list) first.
  • Going past the end. After the last item, next(it) raises StopIteration; next(it, None) gives None instead.
  • Reusing a used-up iterator. A second loop over the same iterator finds nothing; ask the list for a fresh one with iter(...) again.
  • Expecting the list to be used up. Looping over a list twice works fine: each for makes its own new iterator.

Quiz

  1. What does this print?

    it = iter("hey")
    print(next(it), next(it))
  2. What does this print?

    it = iter([10, 20, 30])
    next(it)
    print(list(it))
  3. What does next(it) do when the iterator has nothing left?

    • Raises StopIteration
    • Starts again from the first item
    • Gives back 0
  4. What does this print?

    it = iter([1])
    print(next(it, "empty"), next(it, "empty"))
  5. Which line has a mistake?

    names = ["Ana", "Bo"]
    first = next(names)
    print(first)

Coding tasks

  1. Write first_and_rest(items) that returns a tuple: the first item, and a list of all the others. Use iter and next.

  2. Write count_left(it) that returns how many items an iterator still has (it may already be partly used).

  3. Write next_token(machine) that gives the next item from the iterator machine, or the text "sold out" when it has nothing left.