Skip to contentSkip to navigation

Module 13 · Lesson 01

Iterators and the Iteration Protocol

See what a for loop really does: iterables and iterators, iter() and next(), StopIteration, one-shot iterators, and writing your own iterator class, with a first look at yield.

  • About 9 minutes
  • Builds on earlier lessons
  • 12-question quiz at the end

What you will learn

  • iter() and next() by hand
  • What a for loop really does
  • Write your own iterator
  • Watch an iterator run out

Behind every for loop

Every loop asks the same two questions: give me an iterator, then give me the next item.

  • Iterable

    Anything you can loop over: a list, a string, a range, an open file.

  • iter()

    iter(things) hands back an iterator that remembers its place.

  • next()

    next(it) gives the next item. StopIteration means there are no more.

  • Your own

    A class with __iter__ and __next__ works in any for loop.

Iterators everywhere

Anything that hands out items one at a time is using this protocol.

  • Reading filesA file gives one line per loop, so a huge log never has to fit in memory.
  • PlaylistsNext track: the player asks for one song at a time, never the whole list.
  • Help desksTake the next ticket from the queue, one at a time.
  • Turn orderWhose turn is it? An iterator over the players hands out the answer.

Asking for one more item

This line takes the next item, with a safe answer for when there is none. Tap each part to see its job.

Part 1 of 4

Tap any part of the code below, or press Next.1 of 4 explored

result:Holds whatever next() hands back.

Drive an iterator by hand

Pick an example, change it, then press Run. Say what you expect to see before you press.

Example 1 of 6By hand

iter() makes an iterator. Each next() takes one item.

Your turn: Add a fourth colour. Which line prints it now?

Python
colours = ["red", "green", "blue"]
it = iter(colours)
print(next(it))
print(next(it))
print(next(it, "no more"))
print(next(it, "no more"))
Output
Press Run to see what it prints.

Watch an iterator run out

Press Step to run one line at a time. Watch the names box change.

Ready. Press Step to run the first line.

  1. it = iter(["a", "b"])
  2. first = next(it)
  3. second = next(it)
  4. last = next(it, "end")
  5. print(first, second, last)
  6. print(list(it))

Output so far

Nothing printed yet.

What Python does

Python reads the program from the top. Nothing has run yet.

Names

None yet.

Quick guesses

Guess first, then read why. A wrong guess is where the learning happens. Nothing here is scored.

Question 1 of 6

1.Two iterators over one list:

nums = [1, 2]
a = iter(nums)
b = iter(nums)
print(next(a), next(b))

0 of 6 answered

Common iterator misconceptions

Each card is something learners often believe. Tap it to see what Python really does.

Misconception 1 of 4

Notes

Everything above, in words. Open it when you want the full explanation.

Read the notesOpen

Two roles: iterable and iterator

An iterable is anything you can loop over: a list, a string, a tuple, a dictionary, a set, a range, an open file. An iterator is the object that actually does the looping. It remembers where it has got to and hands out one item at a time.

You turn an iterable into an iterator with the built-in iter(), and you ask an iterator for its next item with next():

Try it 1: edit me, then Run
colours = ["red", "green", "blue"]
it = iter(colours)
print(next(it))   # red
print(next(it))   # green
print(next(it))   # blue
print(next(it))   # raises StopIteration
Output
Press Run to see what it prints.

When an iterator has nothing left, next() raises the exception StopIteration. That is not an error in the usual sense; it is the signal "I am finished".

What a for loop really does

A for loop is a polite wrapper around those two calls. This loop:

Try it 2: edit me, then Run
for colour in colours:
    print(colour)
Output
Press Run to see what it prints.

behaves like this longer code:

Try it 3: edit me, then Run
it = iter(colours)
while True:
    try:
        colour = next(it)
    except StopIteration:
        break
    print(colour)
Output
Press Run to see what it prints.

The loop calls iter() once at the start, then next() again and again, and stops quietly when it sees StopIteration. Every tool that consumes items works the same way: list(), sum(), max(), sorted(), "".join(), unpacking such as a, b = pair, and the in operator.

Iterators are one-shot

An iterator only moves forward. Once it has handed out its last item it is exhausted, and asking again gives nothing:

Try it 4: edit me, then Run
it = iter([1, 2, 3])
print(list(it))   # [1, 2, 3]
print(list(it))   # []
Output
Press Run to see what it prints.

A list is different: it is an iterable, not an iterator, and each for loop calls iter() on it to get a brand new iterator starting at the front. That is why you can loop over the same list as often as you like.

Several built-ins hand you an iterator directly, so they are one-shot too: map(), filter(), zip(), enumerate(), reversed() and an open file. This is the cause of a classic surprise:

Try it 5: edit me, then Run
pairs = zip(["a", "b"], [1, 2])
print(list(pairs))   # [('a', 1), ('b', 2)]
print(list(pairs))   # []  (already used up)
Output
Press Run to see what it prints.

If you need the items more than once, store them in a list first: pairs = list(zip(...)). If you only need them once, keeping the iterator is better, because it never builds the whole collection in memory.

next() with a default

next(it, default) returns default instead of raising StopIteration when the iterator is exhausted. It is the tidy way to take "the first item, if there is one":

Try it 6: edit me, then Run
first_big = next((n for n in [3, 8, 12] if n > 10), None)
print(first_big)   # 12
Output
Press Run to see what it prints.

The thing inside the brackets is a generator expression, which you will meet properly in the next lesson.

Writing your own iterator

Python decides what counts as an iterator by two special methods, the ones with double underscores (often called "dunder" methods):

  • __next__(self) returns the next item, or raises StopIteration when there are none left. next(obj) calls it.
  • __iter__(self) returns an iterator. iter(obj) calls it. For an iterator itself it simply returns self.

Here is a countdown that works in any for loop:

Try it 7: edit me, then Run
class Countdown:
    def __init__(self, start):
        self.current = start

    def __iter__(self):
        return self

    def __next__(self):
        if self.current <= 0:
            raise StopIteration
        value = self.current
        self.current -= 1
        return value

for n in Countdown(3):
    print(n)          # 3, 2, 1
Output
Press Run to see what it prints.

The object keeps its own position in self.current, which is exactly the "where have I got to" memory every iterator needs.

Reusable iterables

Countdown is one-shot, like zip: loop over the same object twice and the second loop is empty, because self.current is already 0. To make something reusable like a list, split the two roles. The iterable's __iter__ creates a fresh iterator each time it is called:

Try it 8: edit me, then Run
class Playlist:
    def __init__(self, songs):
        self.songs = songs

    def __iter__(self):
        return iter(self.songs)   # a new iterator every time
Output
Press Run to see what it prints.

Now every for song in playlist: starts at the first song. Returning iter(...) of a list you already hold is the simplest way to do this.

A shortcut you will use far more: yield

Writing __next__ by hand means managing state and remembering to raise StopIteration. Python has a much shorter way to produce an iterator, the generator function, which uses yield instead of return:

Try it 9: edit me, then Run
def count_up(limit):
    n = 1
    while n <= limit:
        yield n
        n += 1

for n in count_up(3):
    print(n)          # 1, 2, 3
Output
Press Run to see what it prints.

Calling count_up(3) does not run the body. It returns a generator, which is an iterator: each next() runs the body until the next yield, hands that value out, and pauses there. When the body ends, Python raises StopIteration for you. The generators lessons later in this course show what else this can do. For now, the important idea is that generators, lists, files and your own classes all meet the same protocol: iter() to start, next() until StopIteration.

Syntax

The general shape of the statements in this lesson.

syntax.py
it = iter(iterable)          # get an iterator
item = next(it)              # next item, StopIteration at the end
item = next(it, default)     # default instead of StopIteration

class MyIterator:
    def __iter__(self):
        return self          # an iterator is its own iterator
    def __next__(self):
        if finished:
            raise StopIteration
        return value

class MyIterable:
    def __iter__(self):
        return iter(self.items)   # fresh iterator each loop

def gen():                   # generator function: a quick iterator
    yield 1
    yield 2
Output
Press Run to see what it prints.

Worked examples

Read the problem, run the code, then read why it works.

Example 1 of 2

Stepping through a queue by hand

Beginner

A help desk handles tickets in order but must stop for a break after the first two. Take the first two tickets with next(), report them, then show which tickets are still waiting, without losing any.

Python
tickets = ["printer jam", "password reset", "new laptop", "VPN down"]
queue = iter(tickets)

print("Handling:", next(queue))
print("Handling:", next(queue))
print("Break time. Still waiting:", list(queue))
print("Anything left?", next(queue, "nothing"))
print("The list itself is unchanged:", len(tickets))
Output
Press Run to see what it prints.

Predict first

How it works(open after your guess)

The iterator remembers its position, so list(queue) collects only the tickets not yet taken. After that it is exhausted, and next(queue, "nothing") returns the default instead of raising StopIteration. The original list is untouched; only the iterator moved.

Common pitfalls

Mistakes people make with this topic, and what to write instead.

Pitfall 1 of 3

Looping twice over a one-shot iterator

Spot the bug

Can you see what is wrong? Run it to watch it go wrong, then open the fix.

Buggy code: run it
scores = map(int, ['7', '9', '4'])
print(sum(scores))
print(max(scores))
Output
Press Run to see what it prints.
Show what goes wrong and the fix

What happens

Prints 20, then ValueError: max() iterable argument is empty

Write this instead

scores = list(map(int, ['7', '9', '4']))
print(sum(scores))
print(max(scores))

Why it happens

map returns an iterator. sum used up every item, so max receives nothing.

In the real world

Where this shows up in software people use every day.

  1. Reading a paged API one record at a time

    Web services

    A shop's order service returns orders in pages of two. A reporting script wants to treat them as one long stream of orders without caring about pages, so an iterator class fetches the next page only when the current one runs out.

    Why Python fits

    The caller sees a plain stream of orders. The iterator keeps a small buffer and only fetches the next page when the buffer is empty, so a script that stops early never requests pages it does not need. When the last page says there is no next page, __next__ raises StopIteration and the loop ends normally.

    Python
    PAGES = {
        1: {"orders": ["A100", "A101"], "next": 2},
        2: {"orders": ["A102", "A103"], "next": 3},
        3: {"orders": ["A104"], "next": None},
    }
    
    def fetch(page):
        print(f"  (fetching page {page})")
        return PAGES[page]
    
    class Orders:
        def __init__(self):
            self.buffer = []
            self.next_page = 1
    
        def __iter__(self):
            return self
    
        def __next__(self):
            if not self.buffer:
                if self.next_page is None:
                    raise StopIteration
                page = fetch(self.next_page)
                self.buffer = list(page["orders"])
                self.next_page = page["next"]
            return self.buffer.pop(0)
    
    for order in Orders():
        print("order", order)
    Output
    Press Run to see what it prints.

Key takeaways

Tick each one you could explain to a friend.

0 of 5

Common questions

Guess the answer first, then open it.

How can I tell whether something is an iterator or just iterable?

An iterator returns itself from iter(): iter(x) is x is True for an iterator and False for a list. In everyday code you rarely need to check; just remember which built-ins are one-shot.

Can I reset an iterator to the start?

No. Iterators only go forward. Ask the original iterable for a new one with iter(...), or keep the items in a list if you need to go over them again.

Is StopIteration ever something I should catch myself?

Only when you call next() by hand, as in the queue example. Even then next(it, default) is usually neater. Inside a for loop Python handles it for you.

Why would I write an iterator class when I can use yield?

Usually you would not: generator functions are shorter and harder to get wrong. A class is useful when the object needs other methods or attributes as well, such as a remaining() method or a reusable iterable that hands out fresh iterators.

Your notes

Sign in to keep private notes alongside this lesson.

Sign in to take notes

Where to go next

The quiz and the Lab live on their own pages, so this lesson stays about learning.

Finished this lesson?

Create an ID or sign in to save your progress across devices.

Create ID to save
Lessons done in this module0/4 complete
Quiz

Check what you learned

12 questions, with an explanation after every answer. A verified attempt counts towards opening the module Lab.

Lab

Keep going in the Lab

7 tasks on this lesson, from writing code to tracing it by hand. Practice only, no XP.

Review

Spaced review

Questions you miss in a quiz come back on a spaced schedule, so what you learned here sticks.

This lesson at a glance

The 16 lines of code this lesson uses, each with a short note. Keep it open while you do the quiz and the Lab.

What else you can search for and explore

Curious to go further? Each card opens a web search in a new tab.

References

Look things up here whenever you need the exact details.