Skip to content

Iterators, Generators and Next Steps

You will get values one at a time with iterators and generators, then plan your next practice.

10 min read 10 quiz questions

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.

Example: iter() and next()
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

Example: yield creates 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.

Example: a generator expression
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.

Example
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

  1. yield pauses the function and hands out one value.
  2. next() resumes until the next yield.
  3. 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.)

Your notes

Sign in to keep private notes alongside this lesson.

Sign in to take notes

Practice exercise

Not passed yet

Write 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
Want another challenge on this module? More coding practice

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 completed

Create an ID or sign in to save lesson completion across devices.

Create ID to save
Module lesson progress0/5 complete
Module cheat sheet