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

6th Jan 2022, 3:43 PM
NDixit
NDixit - avatar
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
6th Jan 2022, 3:55 PM
CGM
CGM - avatar
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.
7th Jan 2022, 1:20 AM
TallSkinnyHair
TallSkinnyHair - avatar