Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

python
communitycreator
heap
heappush
module

What is heapq.heappush() in Python?

abhilash

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

Answers Code

Overview

The heapq module is an inbuilt module in python. The module offers APIs for different operations of the heap data structure. Also, it provides min heap implementation where the parent key is less than or equal to those of its children. Some of the functions offered by the module are heapify, heappushpop etc.

heappush method

The heappush method inserts the given item onto the heap.

Syntax

heapq.heappush(heap, item)
  • heap: This key refers to the heap to which the item has to be inserted.
  • item refers to the element to be inserted.

Code

import heapq
lst = [28, 2, 32, 22, 10, 1]
print("Original list - ", lst)
heapq.heapify(lst)
print("Heapified list - ", lst)
item_to_push = 0
heapq.heappush(lst, item_to_push)
print("List after inserting 0 - ", lst)

Explanation

  • Line 1: We import the heapq module.
  • Line 3: Define a list of integers called lst.
  • Line 7: Convert the lst to a heap using the heapify method.
  • Line 11: The element to be pushed is defined, i.e, item_to_push.
  • Line 13: item_to_push is inserted to lst using heappush() method.

We can observe that after we insert 0 to the heap, the new smallest element (i.e. 0th index element) is 0 in the output.

RELATED TAGS

python
communitycreator
heap
heappush
module

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

Answers Code
Keep Exploring