0

When I run the following block of code in python, it seems like for input x as a integer, func3 and func4 are correctly capturing the scope of the input. However, if x is an array, func2 sees input x not as [10], but as [9]. Why? Can functions in python change variables outside the scope of that specific function? Ie, it seems like func1 is modifying the global x.

def func1(x):
     x[0] -= 1
     return(x)

def func2(x):
     x[0] -= 2
     return(x)

def func3(x):
     x -= 1
     return(x)

def func4(x):
     x -= 2
     return(x)

if __name__ == "__main__":
    x = [10]
    print(func1(x)) # [9]
    print(func2(x)) # [7]

    x = 10
    print(func3(x)) # 9
    print(func4(x)) # 8
qwer
  • 223
  • 4
  • 13
  • 1
    They have the same scope, but lists are mutable and integers aren't. There's a difference between assigning and setting an item. – jonrsharpe Nov 17 '18 at 22:45
  • See also https://stackoverflow.com/questions/575196/why-can-a-function-modify-some-arguments-as-perceived-by-the-caller-but-not-oth – mkrieger1 Nov 17 '18 at 22:46
  • And https://stackoverflow.com/questions/35431826/why-does-my-function-overwrite-a-list-passed-as-a-parameter – mkrieger1 Nov 17 '18 at 22:47
  • The variable `x` in `func3` is not the same as the variable `x` at the top level, so setting the variable in `func3` doesn’t change the unrelated variable. The variable `x` in `func1` isn’t the same as the variable `x` at the top level either, but you’re not setting the variable; you’re performing an operation on the list that the variable is set to, and that list *is* the same because setting multiple variables to the same value doesn’t copy the value. – Ry- Nov 17 '18 at 22:47

0 Answers0