Heapq Push Pop in Python

Level 3107 keystrokes

This demonstrates heap operations: heapify, push, and pop.

Python code

# heapq turns a plain list into a min-heap
1import heapq
2
# An unsorted list (1 appears twice)
3heap = [3, 1, 4, 1, 5]
# heapify() rearranges the list in place so heap[0] is the smallest item
4heapq.heapify(heap)
# heappush() adds 2 while keeping the heap property
5heapq.heappush(heap, 2)
# heappop() removes and returns the smallest item: prints 1
6print(heapq.heappop(heap))

Output

1
Practice typing this code

Practice typing this code. Results are not recorded in the rankings.

Symbols in this code

The symbols you type in this Python code and how often they appear.

  • ,× 5
  • (× 4
  • )× 4
  • .× 3
  • [× 1
  • ]× 1
  • =× 1

More Python examples at level 3

← Python typing practice