What is the output of this Python code using a custom iterator?
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)
Look at how __next__ decreases self.current and what it returns.
The iterator starts at 3. Each call to __next__ returns the current value before decreasing it. It stops when current is 0.
What is the output of this code snippet?
lst = [10, 20] it = iter(lst) print(next(it)) print(next(it)) print(next(it))
What happens when next() is called but no items remain?
Calling next() on an exhausted iterator raises a StopIteration exception, causing a traceback if not caught.
Which method must a Python object implement to be considered an iterator?
Think about what Python expects when using a for-loop on an iterator.
An iterator must have both __iter__ returning itself and __next__ to get the next item.
What is the output of this code?
def gen(): yield 1 yield 2 g = gen() print(next(g)) print(iter(g) is g) print(next(g))
Generators are their own iterators. What does iter(g) return?
Calling iter() on a generator returns the generator itself, so iter(g) is g is True.
What is the output of this code?
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')
How many times does the iterator yield before stopping?
The iterator yields 'Hi' twice, then raises StopIteration, caught by the except block which prints 'Done'.