1

Can anyone please help me understand what's happening with the scoping in fun1() and fun2(). Naively, I expect both to modify x in-place.

def fun1(t):
    t = t + [2]

def fun2(t):
    t += [2]
    
x = [1]
fun1(x)    
print(x) # output is [1] (I expected [1,2])

x = [1]
fun2(x)
print(x) # output is [1,2] (as expected)
  • It's very important to understand, the issue has **nothing** to do with scope. The scope of the variables are *the exact same* in both functions. The only difference is that `fun2` *mutates* the list (`+=` is a mutator method for lists, and indeed, for all mutable objects that implement it) and `fun1` *does not mutate the list*. `t + [2]` creates *a new list* and assigns it to the local variable `t`. That will not affect the object you passed in. Read the following: https://nedbatchelder.com/text/names.html – juanpa.arrivillaga Jan 16 '21 at 00:59

0 Answers0