Why does heapq.heapify not alter a list when a slice thereof is passed to it?

205 views Asked by At

According to a previous answer

Slicing lists does not generate copies of the objects in the list; it just copies the references to them.

However, when I run the following:

from heapq import heapify
import random as r

def heapfiddling(a):
    heapify(a[1:])
    return a

r.seed(42)
a = [r.randrange(1,100) for i in range(10)]
print("a", a)
print("s", sorted(a))
print("h", heapfiddling(a))

I get

a [82, 15, 4, 95, 36, 32, 29, 18, 95, 14]
s [4, 14, 15, 18, 29, 32, 36, 82, 95, 95]
h [82, 15, 4, 95, 36, 32, 29, 18, 95, 14]

The last print out does not alter the underlying list a. However, when changing the slice from a[1:] to a (where it is passed into heapify), the last print out changes:

h [4, 14, 29, 18, 15, 32, 82, 95, 95, 36]

Why?

0

There are 0 answers