Mutable vs immutable object behavior in python functions

44 Views Asked by At

the two pieces of code below produce different outputs.

def f1(x= []):
    x.append(1)
    return x

print(f1())
print(f1())

Output is:

[1]
[1, 1]

And for the second function:

def f2(x=0):
    x+=1
    return x

print(f2())
print(f2())

Output is:

1
1

Now I know this is because "1" is int type and is immutable (same as if I had used a tuple). What I'm trying to understand is how does this logic work. At the start of both functions you are in the namespace of the respective function, and x has a assigned object to it. How come only in the second case it gets reassigned to "0"? Thanks.

0

There are 0 best solutions below