CodeBlanks Logo Icon CodeBlanks

Generator object

Learn the generator object and next() call.

The generator object

When you call a generator function, it returns a generator object; the function body does not run yet. The next() call advances the body up to the first yield.

Example: g = count_up() returns a generator object. next(g) returns 1 and the function pauses at the first yield. The second next(g) returns 2. When all values are exhausted, a StopIteration error is raised.

StopIteration

When a generator has produced all values, the next() call raises StopIteration. The for loop catches this error and ends the loop silently.

You may see this error in manual next() calls. Example: in the generator g = (x for x in [1]), next(g) returns 1, the second next(g) raises StopIteration. So a for loop is usually safer; manual calls need try/except.

Practice Get values with next

Define the function def gen():; in the body write yield 1 and yield 2. Create a generator object with g = gen(). Print two values with print(next(g)) and print(next(g)).

Starter code

main.py
# gen generator and get values with next

Sample solution

main.py
# gen generator and get values with next
def gen():
    yield 1
    yield 2

g = gen()
print(next(g))
print(next(g))

Expected output

1
2

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 next call

Question
g = count_up()
print(____(g))
Answer
g = count_up()
print(next(g))

Explanation: next(g) produces the next value.

2 What does next() do on an exhausted generator?

  • Returns None
  • Loops forever
  • Restarts
  • Raises StopIteration Correct answer

Explanation: On an exhausted generator next() raises StopIteration.

3 Match the generator object parts

Term Meaning
g = gen() Generator object
next(g) Next value
StopIteration Exhaustion error
for v in g Auto iteration

All lessons in Intermediate