[issue43385] heapq fails to sort tuples by datetime correctly

Steven D'Aprano report at bugs.python.org
Wed Mar 3 06:15:32 EST 2021


Steven D'Aprano <steve+python at pearwood.info> added the comment:

Heaps are not sorted lists! It is true that a sorted list is a heap, but heaps are not necessarily sorted.

Here is another heap which is not sorted:

>>> L = []
>>> for n in (9, 7, 8, 11, 4):
...     heapq.heappush(L, n)
... 
>>> L
[4, 7, 8, 11, 9]


https://en.wikipedia.org/wiki/Heap_(data_structure)


Also:

>>> L = [9, 8, 7, 2, 3, 5, 4, 1, 0, 6]
>>> heapq.heapify(L)
>>> L
[0, 1, 4, 2, 3, 5, 7, 8, 9, 6]


If we change the order of the initial values, the heap changes too:


>>> L = [9, 8, 7, 2, 3, 5, 4, 1, 0, 6]
>>> L.reverse()
>>> heapq.heapify(L)
>>> L
[0, 4, 1, 6, 5, 3, 2, 7, 8, 9]

----------
nosy: +steven.daprano
resolution:  -> not a bug
stage:  -> resolved
status: open -> closed

_______________________________________
Python tracker <report at bugs.python.org>
<https://bugs.python.org/issue43385>
_______________________________________


More information about the Python-bugs-list mailing list