Updating list as function parameter | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 1

Updating list as function parameter

Hi Everyone, Can you please explain how the list x appends the value of 3 in the attached code ? When I print the output of the sum of f() I would have expected to obtain 9 as every time f() is called with no parameters a new list x would be instantiated. Thanks in advance for your support. https://code.sololearn.com/cp9aBvDVcDu9/?ref=app

15th Oct 2021, 11:09 AM
Simone Appella
Simone Appella - avatar
4 Answers
+ 2
Simone Appella Strange code! I have made a little adaptation to your code so we can see what is happening within the function. I think it will explain your output def f(x=[]): x += [3] print(x) return sum(x) print(f() + f() + f())
15th Oct 2021, 11:17 AM
Rik Wittkopp
Rik Wittkopp - avatar
+ 2
Simone Appella I was surprised at the output of your function as I expected f() to run independently. I think the problem is that you have place x=[] as the function argument, so each time it gets called, the argument has changed, similar to re-assigning a variable. If you were to place x=[] external to the function, then assign x+=3 within the func, you would get 9 as your expected answer. I don't know how to check if it is a global variable, but I suspect not. It seems to be a function which is reacting in a recursive manner due to your call format
15th Oct 2021, 11:34 AM
Rik Wittkopp
Rik Wittkopp - avatar
+ 1
Thanks Rik Wittkopp for the tip. As expected every time f() is called with no parameters the previous list gets updated. Is it possible to check whether x is a global variable once instantiated inside the function ?
15th Oct 2021, 11:25 AM
Simone Appella
Simone Appella - avatar
+ 1
By printing globals() I see that x is not included. So the only explanation is that x is defined locally inside f() and once instantiated it remains stored in memory within the scope of the function.
15th Oct 2021, 11:34 AM
Simone Appella
Simone Appella - avatar