Iterators, Generators and Next Steps
You will get values one at a time with iterators and generators, then plan your next practice.
Get one value at a time
An iterator remembers its position in a collection. Call iter() to get an iterator and next() to request its next value.
colors = ['red', 'green', 'blue'] color_iterator = iter(colors) print(next(color_iterator)) print(next(color_iterator)) print(next(color_iterator))
Each call to next() moves forward. A fourth call here would raise StopIteration because there are no values left.
Make a generator
def countdown(start):
while start > 0:
yield start
start -= 1
for number in countdown(3):
print(number)
print('Go!')
A function containing yield is a generator. It pauses after each yielded value and continues when the next value is requested.
squares = (number * number for number in range(1, 5))
for square in squares:
print(square)
Parentheses make this a generator expression, not a list. Generators produce values when needed, so they can save memory when you work with many values.
Where to go next
Build small practice projects, such as a quiz, to-do list, or text adventure. Projects help you combine the skills you have learned.
Explore Python's standard library for built-in tools such as math, json, and pathlib. When a project needs extra packages, learn to use a virtual environment so its packages stay separate from other projects.
Key points
- iter() creates an iterator from a collection.
- next() gets the next iterator value.
- yield turns a function into a generator.
- Generator expressions use parentheses.
- Generators can save memory by producing values on demand.
Worked example
Hand out daily pocket money one day at a time with a generator — values appear lazily, none stored up front.
def pocket_money(amount, days):
for _ in range(days):
yield amount
wallet = pocket_money(20, 3)
print(next(wallet), next(wallet))
How it works, step by step
- yield pauses the function and hands out one value.
- next() resumes until the next yield.
- Nothing beyond the requested days is ever computed.
References & Further Reading
Related entries from PyLabs's own reference library.
- iter() (Return an iterator for a collection or other iterable.)
- next() (Get the next item from an iterator.)
- enumerate() (Pair each item with a counter.)
Practice exercise
Not passed yetWrite a generator function named count_up that yields 1, 2, and 3. Loop over it and print each value on its own line.
# Write your code below
Check yourself
Iterators, Generators and Next Steps quiz
10 questions. You get instant feedback per question, and the timer starts when you press the button.
Lesson incomplete
Not completedCreate an ID or sign in to save lesson completion across devices.