Skip to content
Foxipa
Code Completion 5 Challenges

Complete the Python iterators code

Practice creating and advancing iterators, implementing the iterator protocol, and stopping a callable iterator with a sentinel.

Intermediate ~8 min read

Challenge 1

Complete the code so iterator receives an iterator over numbers.

python Your answer
numbers = [10, 20, 30]
iterator = 

print(next(iterator))

Press Ctrl⌘Enter to check your answer

Challenge 2

Get the next value from the iterator.

python Your answer
iterator = iter(["red", "green"])
first = 

print(first)

Press Ctrl⌘Enter to check your answer

Challenge 3

Complete __iter__ so this iterator returns itself.

python Your answer
class CountDown:
    def __next__(self):
        raise StopIteration

    def __iter__(self):

iterator = CountDown()
print(iterator is iter(iterator))

Press Ctrl⌘Enter to check your answer

Challenge 4

Signal that this iterator has no more values.

python Your answer
class OneValue:
    def __next__(self):
        if self.done:
            
        self.done = True
        return 1

Press Ctrl⌘Enter to check your answer

Challenge 5

Use the callable-and-sentinel form of iter() to read each line until stream.readline() reaches end-of-file.

python Your answer
from io import StringIO

stream = StringIO("red\ngreen\n")
lines = list()
print([line.strip() for line in lines])

Press Ctrl⌘Enter to check your answer