Hone

Lessons · Python · generators run once

A generator only runs once

Things like map(), zip(), filter() and generator expressions produce values on demand; once you have walked to the end, they are empty.

Hone is a place to practise programming. This is one of its lessons, written out in full and free to read without an account.

What it is for

You loop over it to print, then loop again to total, and the total is zero. It happens to everyone once; knowing why makes it a five-second fix.

How to think about it

Ask: will I go through this more than once? If yes, wrap it in list() at the start and use the list. If it is huge and you only need one pass, keep the generator and save the memory.

Worked example

evens = (n for n in range(10) if n % 2 == 0)
A generator: parentheses, not brackets. Nothing computed yet.
print(list(evens))
[0, 2, 4, 6, 8]. Walked to the end.
print(list(evens))
[]. Exhausted. Nothing left to give.

Your turn

Keep the results so they can be used twice.

pairs = (zip(names, scores))
print(pairs)
print(pairs)

The trap

Checking a generator's length with len(). Generators do not know their length; convert to a list first.

Practise generators run once on HoneA question on it now, a coding challenge where there is one, and it is remembered for review. Free, no email needed.