ProgrammingVery hardProduct company OA

What is printed?

What is printed?
it = iter(range(10))
a = list(zip(it, "ab"))
b = next(it)
c = [x for x in it if next(it, 0) % 3]
print(a, b, c)
  1. A. [(0, 'a'), (1, 'b')] 2 [3, 5, 7]
  2. B. [(0, 'a'), (1, 'b')] 3 [4, 6, 8]
  3. C. [(0, 'a'), (1, 'b')] 3 [4, 6]
  4. D. [(0, 'a'), (1, 'b')] 2 [4, 7]

Correct answer: C. [(0, 'a'), (1, 'b')] 3 [4, 6]

zip pulls from its arguments left to right. For the third tuple it first takes 2 from it, then finds the string exhausted and stops – the 2 is already consumed and lost. So next(it) is 3. In the comprehension each kept x is followed by a second next() inside the condition: x = 4 (peeks 5, 5 % 3 = 2, keep), x = 6 (peeks 7, keep), x = 8 (peeks 9, 9 % 3 = 0, drop). Output: [(0, 'a'), (1, 'b')] 3 [4, 6]. Putting the shorter iterable first, zip('ab', it), would not have lost an element.

More Python Programming questions

Exams that ask this topic