1

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?

  • 1
    Why would it? Nothing `heapq.heapify` does to your new list affects the elements or the old list. – user2357112 Oct 17 '20 at 08:07
  • By "new list" are you referring to a[1:]? If so, the element's id()'s (which I assume are logical memory addresses) are the same as those in a (based on the previous stackexchange answer I referenced ) – Wuschelbeutel Kartoffelhuhn Oct 17 '20 at 08:09
  • 1
    _Slicing lists does not generate copies of the objects in the list; it just copies the references to them._ -- yes, but slicing does create a new list object so changes made to its order don't affect the original list, regardless of its contents. In your code that uses `a[:]` (the 1 is odd, it discards the 0-th element), a shallow copy is made of `a` and the new list is passed to `heapify` and is then garbage collected since it has no more references and the function returns the original `a`. When you use `heapify(a)`, you're actually mutating the order of the original `a`. – ggorlen Oct 17 '20 at 18:52
  • Thanks. For some reason, I was under the impression before that heapq.heapify takes the references of the list elements and swaps out the values in these locations. – Wuschelbeutel Kartoffelhuhn Oct 17 '20 at 21:34

0 Answers0