Bird
0
0

What will this code print?

medium📝 Predict Output Q5 of 15
Python - Magic Methods and Operator Overloading
What will this code print?
lst = [10, 20, 30]
it = iter(lst)
print(next(it))
print(next(it))
print(next(it))
print(next(it))
A10 20 30 None
B10 20 30 30
C10 20 30 StopIteration error
D10 20 30 40
Step-by-Step Solution
Solution:
  1. Step 1: Understand iter() and next()

    iter(lst) creates an iterator over the list. next(it) returns next item or raises StopIteration if none left.
  2. Step 2: Trace the calls

    First three next() calls print 10, 20, 30. Fourth next() raises StopIteration error.
  3. Final Answer:

    10 20 30 StopIteration error -> Option C
  4. Quick Check:

    next() raises StopIteration when exhausted [OK]
Quick Trick: next() raises StopIteration when no items left [OK]
Common Mistakes:
  • Expecting next() to return None when exhausted
  • Assuming next() repeats last item
  • Ignoring StopIteration exception

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Python Quizzes