ProgrammingVery hardTCS CodeVita · Infosys HackWithInfy

What is printed?

What is printed?
import heapq
h = []
try:
    heapq.heappush(h, (1, {'a': 1}))
    heapq.heappush(h, (1, {'b': 2}))
except TypeError as e:
    print(type(e).__name__)
print(len(h))
  1. A. TypeError 2
  2. B. TypeError 1
  3. C. ValueError 2
  4. D. No output 2

Correct answer: A. TypeError 2

The second push compares (1, {'b': 2}) with (1, {'a': 1}). The first fields tie, so Python compares the dicts, which do not support <. heappush appends the new item before it sifts up, so the failed comparison still leaves the heap with 2 items.

More Python Programming questions

Exams that ask this topic