Lesson 02
Python iter() and next() — Iterate One Item at a Time
Use iter() and next() to walk an iterable one item at a time, catch StopIteration, and see why iterators skip indexing and slicing.
builds an iterator objectnext(iterator)returns the next value, or raisesStopIteration- No indexing or slicing on the iterator — values arrive on demand
Functions and special functions already looped lists. This lesson focuses on iterators: Netflix analogy, exam papers, iter / next.
.
Netflix does not download 10,000 titles before the first play. You receive one item at a time — not the whole collection at once.
it = iter(["Paper1", "Paper2", "Paper3"])
print(next(it)) # Paper1
print(next(it)) # Paper2
print(next(it)) # Paper3iter() and next()
converts an iterable (str, list, tuple, set, dict, file, …) into an iteratornext()obtains the next element- When nothing remains, Python raises
StopIteration
s = "PYTHON"
itobj = iter(s)
while True:
try:
item = next(itobj)
print(item)
except StopIteration:
breakSome examples mistakenly call next(s) on the original string. After itobj = iter(s) you must call next(itobj). Calling next(s) on a str raises TypeError because a string is iterable, not an iterator.
Tuple demo:
mytuple = ("apple", "banana", "cherry")
myit = iter(mytuple)
print(next(myit))
print(next(myit))
print(next(myit))Rules
- Iterators supply on demand
- No
itobj[0]oritobj[1:3] - A
forloop callsiter/nextfor you and swallowsStopIteration
Interview cheat sheet
| Topic | Answer |
|---|---|
| Convert | iter(obj) |
| Step | next(it) |
| End | StopIteration |
| Indexing | Not on the iterator |
Practice in the playground
- Call
next(itobj)untilStopIteration, then catch it. - Try
itobj[0]and read the error. - Replace the
whilewithfor item in iter(s):.
Loading playground…
Check your understanding
iter() and next() quiz
iter(s) when s is 'PYTHON' returns:
1 / 10