Bird
Raised Fist0

What will be the output of this code?

medium📝 Predict Output Q4 of Q15
Python - Magic Methods and Operator Overloading
What will be the output of this code?
class MyIter:
    def __init__(self):
        self.n = 0
    def __iter__(self):
        return self
    def __next__(self):
        if self.n < 3:
            self.n += 1
            return self.n
        else:
            raise StopIteration

it = MyIter()
print(list(it))
print(list(it))
A[1, 2, 3] followed by []
B[1, 2, 3] followed by [1, 2, 3]
C[] followed by [1, 2, 3]
D[] followed by []
Step-by-Step Solution
Solution:
  1. Step 1: Understand iterator state

    The iterator counts from 1 to 3, then stops. After first list(), the iterator is exhausted.
  2. Step 2: Analyze second list() call

    Since the iterator is exhausted, second list() returns an empty list.
  3. Final Answer:

    [1, 2, 3] followed by [] -> Option A
  4. Quick Check:

    Iterator exhausted after first use, second is empty [OK]
Quick Trick: Iterators remember state; exhausted means empty next time [OK]
Common Mistakes:
MISTAKES
  • Assuming iterator resets automatically
  • Expecting second list() to repeat values
  • Confusing iterable with iterator behavior

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Python Quizzes