Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Functions with mutable default values

I am confused about python's evaluation of default function arguments. As mentioned in the documentation (https://docs.python.org/3.6/tutorial/controlflow.html#more-on-defining-functions)

def f(a, L=[]):
    L.append(a)
    return L

print(f(1))
print(f(2))
print(f(3))

results in

[1]
[1,2]
[1,2,3]

But

def f(a, L=[]):
    L = L+[a]
    return L 

print(f(1))
print(f(2))
print(f(3))

results in

[1]
[2] 
[3]

If L is evaluated only once, shouldn't both the function return the same result? Can someone explain what am I missing here?

This question is different than "Least Astonishment" and the Mutable Default Argument. That question is questioning the design choice while here I am trying to understand a specific case.

like image 570
Umang Gupta Avatar asked Dec 17 '25 17:12

Umang Gupta


1 Answers

In

L.append(a)

you are appending to the same list object in all function calls, as lists are mutable.

whereas in:

L = L+[a]

you're actually rebinding the name L to the concatenation of L and [a]. Then, the name L becomes local to the function. So, in each function call L becomes different after rebinding.

like image 90
heemayl Avatar answered Dec 19 '25 08:12

heemayl



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!