PY-101 ยท Advanced Python
Iterators
โฑ 8 min ๐ Real Python 3 ๐ฌ Animated โ Completed
โก The 30-second answer
An iterable is anything you can loop over, such as a list or a string. Calling iter() on it gives an iterator, an object that hands out one item each time you call next() and raises StopIteration when it runs out. Every for loop does exactly this behind the scenes.
- Use iter() and next()
- Know what StopIteration means
- Write a simple iterator class
Try it
Watch it come alive, run it yourself, then prove it. Real Python, right on this page.
Watch Python run the example. Every variable is a jar; watch the values change and the output appear.
it = iter(["red", "amber", "green"])print(next(it))print(next(it))print(next(it))try:next(it)except StopIteration:print("No more lights")class Countdown:def __init__(self, start):self.n = startdef __iter__(self):return selfdef __next__(self):if self.n == 0:raise StopIterationself.n -= 1return self.n + 1print(list(Countdown(3)))
Change anything and press Run (or Ctrl+Enter). Then open Watch it and press Watch my code.
Input one line per input() call
Press Run to see the output. Python runs in your browser. Expected output
red
amber
green
No more lights
[3, 2, 1] ๐ฏ Use iter() and next() to print the first two items of tasks, then print how many are left using list() on the same iterator (2).
Input one line per input() call
Press Run to see the output. Python runs in your browser. Need a hint?
it = iter(tasks); print(next(it)); print(next(it)); print(len(list(it)))
- The problemA for loop over a million-line file does not load the file first. It asks for one line, then the next, then the next. That "give me the next one" protocol is iteration.
- The Python idea
it = iter(iterable)An iterable is anything you can loop over, such as a list or a string. - In real lifeDatabase libraries return results as iterators, so a query over millions of rows does not need millions of rows in memory.
Start with a question
A for loop over a million-line file does not load the file first. It asks for one line, then the next, then the next. That "give me the next one" protocol is iteration.
Files, database results, zip, map and generators are all iterators. Knowing the protocol explains how they behave.
Explain it like I'm 10
An iterator is a sweet dispenser: each press of the button gives you the next sweet, until it is empty.
The technical explanation
it = iter([1, 2]), then next(it) gives 1, then 2, then raises StopIteration.
A for loop calls iter() once and next() each round, stopping quietly at StopIteration.
A class becomes an iterator by defining __iter__ (return self) and __next__.
Syntax
it = iter(iterable)
next(it) Real-world scenario
Database libraries return results as iterators, so a query over millions of rows does not need millions of rows in memory.
Test yourself
5 questions. Get 4 right and this lesson is marked complete.
Pass the quiz to complete this lesson.
๐ Every lesson counts toward your certificate Next: Generators โQuestions people ask
What is the difference between an iterable and an iterator?
An iterable can produce an iterator (lists, strings, dicts). An iterator remembers its position and gives the next value with next(). Iterators are iterables too.
Why does my zip or map result go empty after one use?
zip and map return iterators, which are used up after one pass. Convert to a list if you need it more than once.
Interview questions
How this topic comes up in Python interviews. Answer out loud first, then open the model answer.
beginner What is the difference between an iterable and an iterator?
An iterable can produce an iterator (lists, strings, dicts). An iterator remembers its position and gives the next value with next(). Iterators are iterables too.
beginner Why does my zip or map result go empty after one use?
zip and map return iterators, which are used up after one pass. Convert to a list if you need it more than once.
intermediate What does next() do?
Returns the next item. It fetches the next value.
intermediate What is raised when an iterator is empty?
StopIteration. StopIteration ends the iteration.
Quick revision
Remember
- Use iter() and next()
- Know what StopIteration means
- Write a simple iterator class
- An iterator is used up once you loop through it. Loop again and you get nothing. Make a fresh one with iter() if you need another pass.
Syntax
it = iter(iterable)
next(it) Official documentation
- Iterators (docs.python.org)