Iterators and generators
Iterables and iterators
Use iter and next to inspect iteration.
Lesson 54 of 63
Reading: about 1 min
Lesson + practice: about 14 min
Difficulty: Intermediate
On this page5 sections
An iterable can produce an iterator. An iterator remembers its position; next() gets one value and raises StopIteration when exhausted. A for loop handles that protocol for you.
Worked example
values = [10, 20]
iterator = iter(values)
print(next(iterator))
print(next(iterator))
print(next(iterator, "done"))10 20 done
Why this works
The two-item list produces two values. The default argument to next avoids an exception after exhaustion.
Another case
numbers = iter([1, 2])
print(list(numbers))
print(list(numbers))[1, 2] []
Practice
Call iter([1]) and then next twice with a default of None.
Check the practice result
Reveal answer
The calls return 1 and then None.
Try another case
What does next(iter([]), "empty") return?
Check your answer
Reveal answer
"empty". The iterator is exhausted immediately, so next() returns the default.
Your progress
Reveal the check answer or reach the end to complete this lesson.