0
def f(a, L=[]):
    L.append(a)
    return L
print(f(1))
print(f(2))
print(f(3))

I don't understand why in the above case the list L is initialized only one time, while in the case below the list is initalized each time the function is called

def f(a, L=None):
    if L is None:
        L = []
    L.append(a)
    return L
print(f(1))
print(f(2))
print(f(3))
user14095422
  • 79
  • 1
  • 7
  • A mutable default argument can result in really weird behaviour. See this, for example: https://stackoverflow.com/questions/57593294/concatenation-of-the-result-of-a-function-with-a-mutable-default-argument – ForceBru Aug 12 '20 at 19:48
  • Honestly, the duplicate doesn't really answer this question. But for the OP, what exactly do you not understand about the second case? In the second case, you explicitly create a new list with the statement `L = []`, which is evaluated every time the function is called. In the first case, you have to know that default parameters are **only evaluated once, when the function is defined** – juanpa.arrivillaga Aug 12 '20 at 19:51
  • @juanpa.arrivillaga since the default parameters are evaluated once, in the second case L should be evaluated only once, which means it should be None only at the first function call (f(1)), but instead it is evaluated even at f(2) and f(3), we know that because the code prints [1], [2], [3], so we enter the if statement at each call of the function, so L is evaluated 3 times, why is it this way? – user14095422 Aug 12 '20 at 20:00
  • @user14095422 No, the default argument is only evaluated once, **that is why** it is always `None`. In any case, you woudln't see the difference with the `None` object, since it is an immutable singleton. You see this very clearly with the mutable list though – juanpa.arrivillaga Aug 12 '20 at 20:17

0 Answers0