Remember
An iterator remembers its position. next() retrieves an item and advances it; exhaustion raises StopIteration unless you supply a default.
An iterator remembers its position. next() retrieves an item and advances it; exhaustion raises StopIteration unless you supply a default.
Follow the example, change its sample, and compare what happens.
Explain the result and test your understanding.
Focus on how the names, objects, and calculations change. We’ll inspect the printed output in the next section.
Follow the code and watch its state change. Guided simulation.
items = range(3)
iterator = iter(items)
print(next(iterator, "done"))
print(next(iterator, "done"))Top-level scope
range(0, 3)Object 2 · range_iterator<range_iterator object>An iterator remembers its position. next() retrieves an item and advances it; exhaustion raises StopIteration unless you supply a default.
(no output)
What do you expect this program to print?
EXAMPLE INSTRUCTIONS
items = range(3)
iterator = iter(items)
print(next(iterator, "done"))
print(next(iterator, "done"))
|
v
DISPLAYED RESULT
0
1
FINAL BINDINGS
items --> object 1 (range)
iterator --> object 2 (range_iterator)
object 1: range(0, 3)
object 2: <range_iterator object>Choose a different sample input, then follow every step through to the output. Before revealing it, predict what the program will display.
Choose a sample and follow its execution. Guided simulation.
items = range(3)
iterator = iter(items)
print(next(iterator, "done"))
print(next(iterator, "done"))Top-level scope
range(0, 3)Object 2 · range_iterator<range_iterator object>The example has finished. Compare the final output with the values and references above.
0 1
What do you expect this program to print?
items = range(3)
iterator = iter(items)
print(next(iterator, "done"))
print(next(iterator, "done"))Python is built for readability and expressiveness. And when it comes to repeating actions or looping through data, iterators power some of Python’s most elegant features. If you’ve used a for loop in Python, you’ve already touched iterators — you just may not have realized it.
An iterator is an object that represents a stream of data — it returns one item at a time when you call next() on it. The iterator remembers where it left off and continues from there, making it highly efficient for looping over large datasets or infinite sequences.
Before diving deeper, let’s differentiate between two terms:
__iter__() and __next__() methods. It produces values one at a time using next().Let’s see a simple example where we manually use an iterator.
numbers = [10, 20, 30]
iterator = iter(numbers)
print(next(iterator)) # Step 1
print(next(iterator)) # Step 2
print(next(iterator)) # Step 3
10
20
30
Once the iterator is exhausted, calling next() again raises a StopIteration exception.
numbers = [10, 20, 30]
iterator = iter(numbers)
print(next(iterator)) # Step 1
print(next(iterator)) # Step 2
print(next(iterator)) # Step 3
print(next(iterator)) # Raises StopIteration
1
Traceback (most recent call last):
...
StopIteration
Typically, we don’t use next() manually. Instead, we let Python handle it through a for loop:
for char in "Hi":
print(char)
H
i
Behind the scenes, Python does:
iter("Hi")next() until StopIteration is raisedYou can create your own iterator by defining a class with __iter__() and __next__() methods.
class Counter:
def __init__(self, limit):
self.limit = limit
self.current = 0
def __iter__(self):
return self
def __next__(self):
if self.current >= self.limit:
raise StopIteration
value = self.current
self.current += 1
return value
count_up_to_3 = Counter(3)
for number in count_up_to_3:
print(number)
0
1
2
hasattr(obj, '__iter__')next() blindly unless you handle StopIteration using a try-except blockfrom collections.abc import Iterator
print(isinstance(iter([1, 2, 3]), Iterator)) # True
print(isinstance([1, 2, 3], Iterator)) # False
True
False
Python iterators offer a powerful way to work with sequences efficiently. Understanding how they work under the hood gives you greater control and performance in your programs.
Connect what you noticed in the example with the idea below.
An iterator remembers its position. next() retrieves an item and advances it; exhaustion raises StopIteration unless you supply a default.
Calling next() restarts the iterator from its first element.
This is the misconception to avoid.Reaching the recap and completing the quizzes are separate milestones.