Recall & Review
beginner
What is the Iterator protocol in Python?
The Iterator protocol is a way Python objects provide a standard way to access elements one at a time, using two methods:
__iter__() and __next__().Click to reveal answer
beginner
What does the
__iter__() method do?The
__iter__() method returns the iterator object itself. It allows an object to be used in a loop like for.Click to reveal answer
beginner
What happens when
__next__() is called on an iterator?The
__next__() method returns the next item from the container. If there are no more items, it raises a StopIteration exception to signal the end.Click to reveal answer
intermediate
How does a
for loop use the Iterator protocol internally?A
for loop calls __iter__() to get an iterator, then repeatedly calls __next__() to get each item until StopIteration is raised.Click to reveal answer
intermediate
How can you make a custom object iterable using the Iterator protocol?
Define
__iter__() to return an iterator object, and define __next__() in that iterator to return items one by one, raising StopIteration when done.Click to reveal answer
Which method must an iterator implement to return the next item?
✗ Incorrect
The __next__() method returns the next item or raises StopIteration when done.
What does the
__iter__() method return?✗ Incorrect
__iter__() returns the iterator object to be used in loops.What exception signals the end of iteration?
✗ Incorrect
StopIteration tells Python that no more items are available.
Which of these is true about an iterable?
✗ Incorrect
An iterable must have an __iter__() method that returns an iterator.
What happens if you call
next() on an iterator with no more items?✗ Incorrect
Calling next() on an exhausted iterator raises StopIteration.
Explain how the Iterator protocol works in Python and why it is useful.
Think about how Python loops over things like lists or files.
You got /5 concepts.
Describe how you would create a custom iterator for your own object.
Focus on the two special methods needed.
You got /3 concepts.