0
0
Pythonprogramming~5 mins

Iterator protocol in Python - Cheat Sheet & Quick Revision

Choose your learning style9 modes available
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?
A__next__()
B__iter__()
C__getitem__()
D__call__()
What does the __iter__() method return?
AThe iterator object itself
BA list of all items
CThe first item
DNone
What exception signals the end of iteration?
ATypeError
BIndexError
CValueError
DStopIteration
Which of these is true about an iterable?
AIt raises StopIteration immediately
BIt has an __iter__() method
CIt has a __next__() method
DIt is always a list
What happens if you call next() on an iterator with no more items?
ARaises TypeError
BReturns None
CRaises StopIteration
DReturns the last item again
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.