ProgrammingHardProduct-company MCQ pattern

What is printed?

What is printed?
class R:
    def __iter__(self):
        print("it", end=" ")
        return iter([1, 2, 3])

r = R()
print(2 in r, 5 in r)
  1. A. True False
  2. B. it True False
  3. C. it it True it False
  4. D. it it True False

Correct answer: D. it it True False

R has no __contains__, so the in operator falls back to iterating via __iter__. Each in creates a fresh iterator, so "it" is printed twice, and both are printed while print's arguments are being evaluated, i.e. before the final line's values appear. 2 is found, 5 is not: True False.

More Python Programming questions

Exams that ask this topic