[Python] How does heapq affect list that is not heapified?

Discussão em 'Python' iniciado por Stack, Março 15, 2025.

  1. Stack

    Stack Membro Participativo

    This is a curious exercise to understand the inner workings of heapq and why heapify is done.

    Experiment 1

    from heapq import heappush, heappop

    data = [3,2,1]
    # heappush(data,4)
    heappop(data),heappop(data),heappop(data)#,heappop(data)


    Output: (3, 1, 2).

    What did heappop do to the list to make 1 and 2 swap positions? Which of the first two heappops did this?

    Experiment 2 (pushing 1 element + popping 1 more)

    data = [3,2,1]
    heappush(data,4)
    heappop(data),heappop(data),heappop(data),heappop(data)


    Output: (3, 1, 2, 4)

    Experiment 3 (change pushed element from 4 to 0)

    data = [3,2,1]
    heappush(data,0)
    heappop(data),heappop(data),heappop(data),heappop(data)


    Output:: (0, 1, 2, 3)

    Why when pushing 4, the output seems similar to experiment 1 (Please compare mechanics of experiment 1 and experiment 2), but when pushing 0, the other 3 elements also changed positions?

    It looks like pushing 0 instead of 4 turned the list into a real heap?

    P.s I know heapify(data) can turn experiment 3 output to (1, 2, 3, 4), making it work normally is not the point of the question.

    Continue reading...

Compartilhe esta Página