1

From https://www.tutorialspoint.com/heap-queue-or-heapq-in-python:

heappush – This function adds an element to the heap without altering the current heap.

If the current heap is not altered, why don't we use the append() list method? Is the list with the new element heapified only when heappop() is called?

Am I misunderstanding "without altering the current heap"? Or something else?

Robin Andrews
  • 3,514
  • 11
  • 43
  • 111
  • Maybe it means that the function returns a new heap with the additional element (i.e., that the heap is not changed in-place). – goodvibration Jul 01 '20 at 14:39
  • Oh, well, according to the `Inserting into heap` section that appears on the same page further below, that's not the case. – goodvibration Jul 01 '20 at 14:40
  • I think the answer to your question is that the heap must always abide the rule `length == 2**n - 1` for some integer value of `n`. So `heappush` is different from `append` in the fact that it may decide it's time to increase the size of the heap by (almost) 2. – goodvibration Jul 01 '20 at 14:42
  • I think it's just bad English. I mean how can you add something to something else without altering the first something? When I use `heappush()` with a lower value than any currently in the list, it is placed at the start of the list. – Robin Andrews Jul 01 '20 at 14:44
  • Yeah, the documentation actually says - add to the end of the list. And if still in doubt, the coding example that follows shows it explicitly. So obvious "without changing the heap" is plain wrong. – goodvibration Jul 01 '20 at 14:46

2 Answers2

1

This is not an official reference documentation. So it contains what its author wanted to write.

If you consult the official Python Standard Library reference, you will find:

heapq.heappush(heap, item): Push the value item onto the heap, maintaining the heap invariant.

Here what happens is clear: the new item is added to the collection, and the internal structure is enventually adapted to have the binary tree respect: every parent node has a value less than or equal to any of its children.

After a second look at the tutorial, I think that what is meant is that heappush adds the new element without altering other elements on the heap, by opposition to heappop or heapreplace which will remove the current smaller item.

Serge Ballesta
  • 143,923
  • 11
  • 122
  • 252
0

I believe the "without altering the current heap" means "maintaining the heap property that each node has a smaller key than its children". If you need the heap data structure, list.append() would not suffice. You may like to refer to https://www.cs.yale.edu/homes/aspnes/pinewiki/Heaps.html.

Neo
  • 111
  • 3