Skip to content

Heap became unsorted while calling heappush #132110

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
PC-Killer opened this issue Apr 5, 2025 · 1 comment
Closed

Heap became unsorted while calling heappush #132110

PC-Killer opened this issue Apr 5, 2025 · 1 comment
Labels
type-bug An unexpected behavior, bug, or error

Comments

@PC-Killer
Copy link

PC-Killer commented Apr 5, 2025

Bug report

Bug description:

Read the code below:

import heapq


heap = []
heapq.heappush(heap, (2, 2))
heapq.heappush(heap, (1, 2))
heapq.heappush(heap, (1, -1))
print(heap)

It is very simple, and obviously, it should print "[(1, -1), (1, 2), (2, 2)]".
But here is what it prints:

PC-Killer@nixos ~> python --version ; cat -n ~/python_work/bugs/unordered_heap.py ; python ~/python_work/bugs/unordered_heap.py
Python 3.14.0a4
     1  import heapq
     2
     3
     4  heap = []
     5  heapq.heappush(heap, (2, 2))
     6  heapq.heappush(heap, (1, 2))
     7  heapq.heappush(heap, (1, -1))
     8  print(heap)
[(1, -1), (2, 2), (1, 2)]

The heap became unsorted.

CPython versions tested on:

3.14

Operating systems tested on:

Linux

@PC-Killer PC-Killer added the type-bug An unexpected behavior, bug, or error label Apr 5, 2025
@graingert
Copy link
Contributor

heapq doesn't need to maintain a sorted list, it just needs to maintain a heap invariant such that heappop returns the smallest item.

import heapq

items = [(2, 2), (1, 2), (1, -1)]

heap = []
heapq.heappush(heap, items[0])
heapq.heappush(heap, items[1])
heapq.heappush(heap, items[2])

items2 = [
    heapq.heappop(heap),
    heapq.heappop(heap),
    heapq.heappop(heap),
]
assert items2 == sorted(items)
print(items2)

You could open a discussion in https://discuss.python.org/c/help/7

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
type-bug An unexpected behavior, bug, or error
Projects
None yet
Development

No branches or pull requests

2 participants