ProgrammingHardTCS CodeVita · Infosys HackWithInfy

What is printed?

What is printed?
import heapq
h = []
for t in [(2, 'b'), (2, 'a'), (1, 'z')]:
    heapq.heappush(h, t)
print([heapq.heappop(h) for _ in range(3)])
  1. A. [(2, 'a'), (2, 'b'), (1, 'z')]
  2. B. [(2, 'b'), (2, 'a'), (1, 'z')]
  3. C. [(1, 'z'), (2, 'a'), (2, 'b')]
  4. D. [(1, 'z'), (2, 'b'), (2, 'a')]

Correct answer: C. [(1, 'z'), (2, 'a'), (2, 'b')]

Tuples compare field by field, so the heap pops (1, 'z') first and then breaks the tie of 2 with the string 'a' before 'b'.

More Python Programming questions

Exams that ask this topic