1

This is a very simple problem but I have no idea why python is doing this. For the loop below, the if head != None... is creating a local variable such that the head += 1 is not modifying the head in for head in myHeap.array. adding a print(head) right after the head += 1 is producing the result I want, but the head outside the if statement remains the same.

    for head in myHeap.array:
        if head != None and count % int(grow) == 0:
            head += 1

so the input myHeap.array = [2, 2, 2, 1] outputs the same list at the end of the iteration, when [3, 3, 3, 2] is expected. I have also verified that the condition is met for the if statement and the interpreter uses the head += 1 line

2 Answers2

4

You would need to access the elements of the myHeap.array list to modify them. Something like this:

class myHeap(object):
    pass

myHeap.array = [2, 2, 2, 1]

for n, head in enumerate(myHeap.array):
    if head != None:
        myHeap.array[n] = head + 1

print myHeap.array

output:

[3, 3, 3, 2]
Holy Mackerel
  • 3,259
  • 1
  • 25
  • 41
0

Run this and look closely at the IDs generated.

listt = [2, 3]

for i in listt:
    print(id(i))
    i += 1
    print(id(i))
    print()

print(listt)
print()

for i in range(len(listt)):
    print(id(listt[i]))
    listt[i] += 1
    print(id(listt[i]))
    print()

print(listt)

What is happening in your code is that object reference in temporary variable is updated so it no longer contains a reference to the object in the list. Hence you don't see the changes in the list. You need to update the references in the list elements. For that you need to access those variables directly i.e. by subscript.

Aseem Bansal
  • 6,722
  • 13
  • 46
  • 84