Iterator class versus iterable class
Countdown is used up after one pass. Playlist gives a fresh iterator every time. Change Playlist.__iter__ to return self and see what breaks.
A for loop asks an object for an iterator with iter(), then calls next() on it again and again until it raises StopIteration. Knowing the difference between an iterable (can be looped over) and an iterator (remembers its place, used up once) explains many surprises.
Change the code and press Run (Ctrl+Enter). Predict what will happen first, then break it on purpose and read what changes. Your edits are saved and match the lesson page.
Ready for more? This phase has 6 hands-on exercises with automatic checks.
Practice questions
Write the code in the editor, run it, then open the model answer to compare.
Use iter and next by hand to print the three letters of "abc", one per line, and then show what next(it, "done") returns afterwards.
Write an iterator class Evens that takes a limit and produces the even numbers from 0 up to but not including limit. Print list(Evens(7)).
Write an iterable class Words that takes a sentence and loops over its words. Show that you can loop over the same object twice.
Explain it without notes
Explain what a for loop does, step by step, in terms of iter and next.
What is the difference between an iterable and an iterator? Give an example of each and say which one can be looped over twice.
How do you write an iterator class, and what makes it different from an iterable class?
Why does looping over the same iterator a second time produce nothing, and how do you avoid the bug?
What goes wrong if you add or remove items from a list while looping over it, and what happens with a dictionary?
Expected output
first pass: [3, 2, 1]
second pass: []
first pass: ['intro', 'verse', 'chorus']
second pass: ['intro', 'verse', 'chorus']
tick 2
tick 1