Infinite Generators in Python: Running State
An infinite generator has no built-in final value. It produces another value whenever you request one.
You will use while True with yield and keep changing values between requests. Prerequisites: arithmetic, variables, loops, and Python yield: Write a Generator Function. No imports are needed.
Yield inside an endless loop
def even_numbers(): number = 2 while True: yield number number += 2values = even_numbers()for _ in range(5): print(next(values))This prints 2, 4, 6, 8, 10. The generator has no fixed limit, but the printing loop makes only five requests. _ is a loop variable whose value we do not need.
Each next() resumes the function until its next yield. The function remembers number while paused. It does not run endlessly in the background.
Keep a running total
A running total remembers everything added so far. You can keep both a total and the next amount to add.
amount = 3total = 0for _ in range(4): total += amount print(total) amount += 2This prints 3, 8, 15, 24: the amounts added were 3, 5, 7, 9. Update the total before displaying it. A generator can preserve these variables between requests too.
Choose where the sequence ends
Use a finite generator when the sequence has a known end. Use an infinite generator when its caller decides how many values to take. A bounded for _ in range(5) loop makes five requests; it does not finish the generator.
Do not use list(values) or an unbounded for value in values to consume an infinite generator: there is no last value. These examples use fixed requests to keep the output short.
See also: Python Generator close(): Stopping a Generator.
Your turn
Write tens(), an infinite generator producing 10, 20, 30, and so on. Print only its first four values using next().
10 20 30 40
# Define tens(), then request and print four values.