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.StopIterationmeans 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
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?
colours = ["red", "green", "blue"] it = iter(colours) print(next(it)) print(next(it)) print(next(it, "no more")) print(next(it, "no more"))
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.
- it = iter(["a", "b"])
- first = next(it)
- second = next(it)
- last = next(it, "end")
- print(first, second, last)
- 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 notesNotesOpenClose
Syntax
The general shape of the statements in this lesson.
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 2Press 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
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.
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))Press Run to see what it prints.Predict first
How it works(open after your guess)
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.
scores = map(int, ['7', '9', '4']) print(sum(scores)) print(max(scores))
Press Run to see what it prints.Show what goes wrong and the fixWhat goes wrong and the fix
In the real world
Where this shows up in software people use every day.
- Web services
Reading a paged API one record at a time
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.PythonPAGES = { 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)OutputPress 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?
Can I reset an iterator to the start?
Is StopIteration ever something I should catch myself?
Why would I write an iterator class when I can use yield?
Your notes
Sign in to keep private notes alongside this lesson.
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.
Check what you learned
12 questions, with an explanation after every answer. A verified attempt counts towards opening the module Lab.
Keep going in the Lab
7 tasks on this lesson, from writing code to tracing it by hand. Practice only, no XP.
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.