0

Can anyone explain why the outputs are different in these two cases:

Case 1:

Input:

def fun1(x,z=[]):
    z.append(x)
    return z

def fun2(a):
    print(fun1(a))
    print(fun1(a))

fun2([1])

Output:

[1]
[1, 1]

Case 2:

Input:

def fun1(x,z):
    z.append(x)
    return z

def fun2(a):
    print(fun1(a, []))
    print(fun1(a, []))

fun2([1])

Output:

[1]
[1]
U12-Forward
  • 65,118
  • 12
  • 70
  • 89
  • In case 2, you're supplying a fresh empty list [] at every call. In case 1, you're only supplying a fresh empty [] the first time fun1 is called; then, the same list is used every time. The "suprising" thing here, is the order of evaluation: `z=[]` values of default arguments are only evaluated once. Try this function: `def fun3(x=print('Initialization')): print('Execution')` and see if you can understand what is happening. – Stef Sep 17 '21 at 10:50

0 Answers0