Manual Iteration with next()
Intermediate · Predict the output · from Python Iterators: How for Loops Really Work Under the Hood
From the lesson: How Does the Iterator Protocol Work?
The iterator protocol is a contract. Any object that implements two special methods - __iter__() and __next__() - is an iterator. That's it. No inheritance required, no registration, just those two methods.
Read this part of the lessonPredict what the following code will print. Think carefully about when StopIteration is caught.
nums = [10, 20, 30]
it = iter(nums)
print(next(it))
print(next(it))
print(next(it, 'done'))
print(next(it, 'done'))Write four print() statements that produce the exact same output.
# Predict the output of the code above
# Write four print statements that produce the same result
print(10)
# Fix the remaining lines
print("?")
print("?")
print("?")
More Iterator exercises
- Build a Range-Like IteratorAdvanced
- Fix the Broken IteratorIntermediate
- Cycle Through TeamsIntermediate
- Build a Fibonacci IteratorAdvanced
- Chain and Filter with itertoolsAdvanced
All Python exercises · 50 practice problems · Advanced Python quiz