0

Why does calling several times in a row the following function:

a = []

def test(a,b):
    if b > 0:
        a.append(1)
        return a

with test(a,4), it enlarges the list a each time, but calling several times in a row the function:

a = 0

def test(a,b):
    if b > 0:
        a += 1
        return a

with test(a,4) returns 1 every single time instead of 1, 2, 3, etc.?

It looks like lists get updated by a function and retain their updated value even after the function finished to execute, while this behavior doesn't hold for integers (and I guess floats and several other types).

  • 1
    Because in one case you're explicitly updating one mutable list object, and in the other you're creating new immutable integer objects. – jonrsharpe Sep 11 '17 at 20:03
  • See this answer [here](https://stackoverflow.com/a/28567293/7269282) for a good explanation of this behaviour. – EdW Sep 11 '17 at 20:13

1 Answers1

0

Integers are immutable; lists are mutable. a += 1 changes the value of a by reassigning the value it refers to. a.append(1) adds the value 1 to the list that a refers to, without changing the reference itself.

In your test function, a if a reference within the function's scope; not the same reference as a in the global scope. However, when passing a mutable object, the reference remains the same; allowing for the object to be modified without the need to reassign the variable. In your function

def test(a, b):
    if b > 0:
        a += 1
        return a

The value of a is modified relative to test. To reassign the value globally, you need to perform that action in the global scope (or use the global keyword). So, instead of test(a, 4), use a = test(a, 4) to reassign the value of a.

Zach Gates
  • 4,045
  • 1
  • 27
  • 51