0
0
Pythonprogramming~20 mins

Iterator protocol in Python - Practice Problems & Coding Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
Iterator Protocol Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
Predict Output
intermediate
2:00remaining
Output of custom iterator class

What is the output of this Python code using a custom iterator?

Python
class CountDown:
    def __init__(self, start):
        self.current = start
    def __iter__(self):
        return self
    def __next__(self):
        if self.current <= 0:
            raise StopIteration
        self.current -= 1
        return self.current + 1

for number in CountDown(3):
    print(number)
A1\n2\n3
B2\n1\n0
C4\n3\n2
D3\n2\n1
Attempts:
2 left
💡 Hint

Look at how __next__ decreases self.current and what it returns.

Predict Output
intermediate
2:00remaining
Output of iter and next with list

What is the output of this code snippet?

Python
lst = [10, 20]
it = iter(lst)
print(next(it))
print(next(it))
print(next(it))
A10\n20\nStopIteration
B10\n20\nTraceback (most recent call last): StopIteration
C10\n20\nNone
D10\n20\n0
Attempts:
2 left
💡 Hint

What happens when next() is called but no items remain?

🧠 Conceptual
advanced
1:30remaining
Understanding iterator protocol methods

Which method must a Python object implement to be considered an iterator?

A__iter__ only
B__next__ only
C__iter__ and __next__
D__call__
Attempts:
2 left
💡 Hint

Think about what Python expects when using a for-loop on an iterator.

Predict Output
advanced
2:00remaining
Output of generator and iterator interaction

What is the output of this code?

Python
def gen():
    yield 1
    yield 2

g = gen()
print(next(g))
print(iter(g) is g)
print(next(g))
A1\nTrue\n2
B1\nTrue\nStopIteration
C1\nFalse\n2
D1\nFalse\nStopIteration
Attempts:
2 left
💡 Hint

Generators are their own iterators. What does iter(g) return?

Predict Output
expert
2:30remaining
Output of nested iterator with StopIteration handling

What is the output of this code?

Python
class Repeater:
    def __init__(self, value, times):
        self.value = value
        self.times = times
        self.count = 0
    def __iter__(self):
        return self
    def __next__(self):
        if self.count >= self.times:
            raise StopIteration
        self.count += 1
        return self.value

r = Repeater('Hi', 2)
it = iter(r)
try:
    while True:
        print(next(it))
except StopIteration:
    print('Done')
AHi\nHi\nDone
BHi\nDone
CHi\nHi
DDone
Attempts:
2 left
💡 Hint

How many times does the iterator yield before stopping?