Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • Python Tutorial
  • Interview Questions
  • Python Quiz
  • Python Glossary
  • Python Projects
  • Practice Python
  • Data Science With Python
  • Python Web Dev
  • DSA with Python
  • Python OOPs
Open In App
Next Article:
Python hash() method
Next article icon

Python heapq.heapify() Method

Last Updated : 17 Mar, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

The heapq.heapify() function in Python is used to transform a regular list into a valid min-heap. A min-heap is a binary tree where the smallest element is always at the root. This method is highly useful when you need to create a heap structure from an unordered list and maintain the heap property efficiently.

Example: Converting a List into a Min-Heap

Python
import heapq  # Create a regular list a = [3, 1, 5, 7, 9, 2]  # Convert the list into a heap heapq.heapify(a)  print("Min-Heap:", a) 

Output
Min-Heap: [1, 3, 2, 7, 9, 5] 

Explanation:

  • The list [3, 1, 5, 7, 9, 2] is rearranged so that the smallest element (1) is at the root of the heap.
  • After the operation, the heap is [1, 3, 2, 7, 9, 5], where 1 is the smallest element.

Syntax of heapify() method

heapq.heapify(iterable)

Parameters

  • iterable: The iterable (usually a list) that you want to convert into a heap. This list will be rearranged in place to satisfy the heap property (for min-heaps, the smallest element will be at the root).

Return Value

The heapq.heapify() method does not return anything. It modifies the input list in place, ensuring that the list satisfies the heap property, where the smallest element is at the root.

How Does heapq.heapify() Work?

  • The heapq.heapify() function rearranges the elements in the list to make it a valid min-heap.
  • The heap property is maintained after this operation, so the smallest element will always be at index 0.
  • It runs in O(n) time complexity, where n is the number of elements in the list. This is more efficient than using heapq.heappush() repeatedly to insert elements, which would take O(n log n) time.

Examples of heapify() method

1. Using heapq.heapify() on a Custom List

Python
import heapq  # Create a custom list a = [8, 4, 3, 9, 2, 5]  # Convert the list into a heap heapq.heapify(a)  print("Heapified List:", a) 

Output
Heapified List: [2, 4, 3, 9, 8, 5] 

Explanation:

  • The list [8, 4, 3, 9, 2, 5] is rearranged so that the smallest element (2) is at the root of the heap.

2. Using heapq.heapify() to Implement a Priority Queue

Python
import heapq  # List of tasks with (priority, task) a = [(2, "Task A"), (1, "Task B"), (3, "Task C")]  # Convert the list into a heap heapq.heapify(a)  # Pop the task with the highest priority (lowest priority value) priority, a = heapq.heappop(a)  print("Highest priority task:", a) 

Output
Highest priority task: Task B 

Explanation:

  • The list of tasks is converted into a heap, where tasks are processed based on their priority.
  • The task with the smallest priority value (highest priority) is popped first, in this case, Task B.

When to Use heapq.heapify()?

You can use heapq.heapify() when you need to efficiently create a heap from an unordered list. Some common use cases include:

  • Priority Queues: When tasks or elements need to be processed based on priority, and you want to quickly convert an unordered list into a priority queue.
  • Graph Algorithms: When using algorithms like Dijkstra's Shortest Path or A Search*, which often require the use of heaps.
  • Efficient Sorting: When performing heap sort, where the elements are repeatedly popped from the heap to get them in sorted order.
  • Merging Sorted Lists: When merging multiple sorted lists or processing data that can be efficiently handled by a heap structure.

Next Article
Python hash() method

B

brijkan3mz4
Improve
Article Tags :
  • Python
  • Data Structures-Heap
  • Python-DSA
Practice Tags :
  • python

Similar Reads

  • Python heapq.heappop() Method
    The heapq.heappop() function in Python is used to pop and return the smallest element from a heap, maintaining the heap property. This function is extremely useful in situations where the smallest element in a min-heap needs to be processed first, such as in priority queues or sorting algorithms. Ex
    4 min read
  • Python heapq.heappushpop() Method
    The heapq.heappushpop() method is part of Python's heapq module, which provides an efficient way to implement heaps (also known as priority queues). This method is a combination of two operations: heappush() and heappop(). It allows you to push a new element onto the heap and then pop the smallest e
    5 min read
  • Python heapq.heapreplace() Method
    The heapq.heapreplace() function removes and returns the smallest element from a heap (the root) and inserts a new item into the heap, all while maintaining the heap property. This is more efficient than performing separate heappop() and heappush() operations because it minimizes the number of heap
    4 min read
  • Python heapq.merge() Method
    The heapq.merge() method in Python is part of the heapq module, which is used for heap-related operations. This method allows you to merge multiple sorted input iterables into a single sorted output iterable, efficiently using the heap data structure. It is particularly useful when working with sort
    4 min read
  • Python hash() method
    Python hash() function is a built-in function and returns the hash value of an object if it has one. The hash value is an integer that is used to quickly compare dictionary keys while looking at a dictionary. Python hash() function SyntaxSyntax : hash(obj) Parameters : obj : The object which we need
    6 min read
  • Python heapq.nlargest() Method
    The heapq.nlargest() method in Python is a useful function from the heapq module that returns the n largest elements from an iterable, such as a list or tuple. This method is particularly handy when we want to quickly find the largest elements from a dataset, using a heap-based approach. Basic Examp
    4 min read
  • Heap queue or heapq in Python
    A heap queue or priority queue is a data structure that allows us to quickly access the smallest (min-heap) or largest (max-heap) element. A heap is typically implemented as a binary tree, where each parent node's value is smaller (for a min-heap) or larger (for a max-heap) than its children. Howeve
    7 min read
  • Python heapq.nsmallest() Method
    The heapq.nsmallest() method in Python is part of the heapq module and is used to retrieve the n smallest elements from an iterable, such as a list, tuple or other iterable objects. This method is highly useful when you need to efficiently find the smallest elements in a dataset, without sorting the
    4 min read
  • Python __add__() magic method
    Python __add__() function is one of the magic methods in Python that returns a new object(third) i.e. the addition of the other two objects. It implements the addition operator "+" in Python. Python __add__() Syntax Syntax: obj1.__add__(self, obj2) obj1: First object to add in the second object.obj2
    1 min read
  • Python List copy() Method
    The copy() method in Python is used to create a shallow copy of a list. This means that the method creates a new list containing the same elements as the original list but maintains its own identity in memory. It's useful when you want to ensure that changes to the new list do not affect the origina
    3 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences