← Python lessons

Python Generators: Your First Generator and next()

Part of a free Python course — sign up to save your progress and get AI hints.Sign up free

A generator gives you values one at a time, as you ask for them.

You will create a generator expression and request its values with next(). Prerequisites: variables, lists, arithmetic, and print(). All examples run in Python without imports.

Use a generator when you want to consume calculated values one at a time. Use a list when you need to index values or read them repeatedly. A generator remembers its position and does not restart.

Ask for a value with next()

numbers = (x for x in [1, 2, 3])print(next(numbers))  # 1print(next(numbers))  # 2print(next(numbers))  # 3

This prints 1, 2, and 3 on separate lines.

numbers stores a generator. next(numbers) asks it for one value, and print() displays that value. Each call moves forward: it does not start again at 1.

Make a generator expression

Look at this line:

numbers = (x for x in [1, 2, 3])

The parentheses around x for x in [1, 2, 3] make a generator expression. Read it as “give me x for each x in this list.” The list supplies the inputs; the generator produces each result when asked.

You can change the expression before for to calculate each result:

doubled = (x * 2 for x in [1, 2, 3])print(next(doubled))  # 2print(next(doubled))  # 4print(next(doubled))  # 6

The first request calculates 1 * 2, the second calculates 2 * 2, and the third calculates 3 * 2.

Powers use **

* multiplies; ** raises a number to a power. For example, 3 ** 1 is 3, 3 ** 2 is 9, and 3 ** 3 is 27.

To generate powers, put a power calculation before for.

A generator can run out

These generators have only three values. A fourth next() call raises a StopIteration error because there are no values left. Creating a new generator starts a new sequence.

For this exercise, make one generator and ask for exactly three values.

single = (x for x in [7])print(next(single))  # 7print(next(single))  # this line raises StopIteration: no values remain

This prints 7, then raises StopIteration on the second request.

See also: Python yield: Write a Generator Function.

Your turn

Create a generator expression named increased that adds 10 to each value in [1, 2]. Print its two values using next().

🎯 Goal — make it print exactly:
11
12
# Create increased, then print its two values with next().