0
def test(list2):
    list2.append(1)
    print len(list2)
    print len(LIST1)

LIST1 = [1]

while len(LIST1) < 9:
    test(LIST1)

Please explain why 'LIST1' is increasing in size if I'm appending to 'list2', isn't variables inside functions local? And above all, how can I circumvent this?

The same happens if I make a new variable:

def test(arg_list):
    list2 = arg_list
    list2.append(1)
    print len(list2)
    print len(LIST1)

LIST1 = [1]

while len(LIST1) < 9:
    test(LIST1)
f.rodrigues
  • 3,499
  • 6
  • 26
  • 62

1 Answers1

1

No, parameters passed to a function are by reference, and in the second example the local variable is yet another reference to the same list. Parameter passing and variable assignment do not create copies of the list, only references to the same object. In other words: anything you do to an object being referenced inside the function (say, a list) will be reflected on the object itself once the function exits - the function parameter and the object "outside" the function are one and the same.

How can you circumvent this? well, if it fits your usage scenario you can simply copy the list before passing it as a parameter, like this:

test(LIST1[:])

The above will create a new, different list (it's a shallow copy, though ... for performing a deep copy use copy.deepcopy), which you can safely modify inside the function, as the list "outside" the function will remain unchanged.

Óscar López
  • 232,561
  • 37
  • 312
  • 386