0
Python question
def f(x=[]): x += [3] return sum(x) print(f()+f()+f()) Can anyone explain why this code return value 18 I thought each time I will get fresh parameter
2 Answers
+ 1
It is a bit strange, but what obviously happens is that in each call to f () [3] is added to the existing x
put some print () to check what happens inside the function, or call f () in separate prints
0
I think what's happening here is the print function is printing the return from f() added to itself three times as a mathematical operator. It prints something like 3 + (3+3) + (3+3+3) which adds up to 18.
If you want to print the numbers individually three times, you could convert them into a list or individual strings, or just use three separate print calls.