+ 1

What is the output of this code? def f(x=[]): x+=[3] return sum(x) print(f()+f() + f())

plase solve this question , elaborate ans is 18 how it comes

12th Feb 2023, 7:44 AM
Gaurav Ghadge
Gaurav Ghadge - avatar
2 Réponses
+ 3
Hi, Gaurav Ghadge ! When you set a default value in a function to a mutable object like a list, it will peserve the statement, so the next time you call the function it will continue where you left it. So in your case f() -> x = [3] (as a local variable), next time f() -> x = [3, 3] etc. So to avoid this, when you define your function, set x=None as default, and then assign the mutual object inside the function instead.
12th Feb 2023, 1:26 PM
Per Bratthammar
Per Bratthammar - avatar
+ 1
# You can look at these examples below. When you create a mutable object as a default keyword argument, it will hang on to the functions local scopes, as long as you don't assign anytning to the (keyword) variable (as a real assignment). The function gets the id when it’s defined, and is the same in all calls. # So, as long as you just do inplace changes at the obiect, it will live on (it is the same object and so it has the same object id.) So when you call the function again, it don’t create a new default object, because it already exist. # If you instead make an ordinary assignment, you create a new object, and you got an new obect id. # That's is why it is better to do the assignment inside the finction body istead, if you don't really want this state preserving property. def f(x=[]): x += [3] # Inplace change. print(f"Inplace: {id(x) = }; {x = }") f() f() f() print() def g(x=[]): x = x + [3] # Assignment. print(f"Assignment: {id(x) = }; {x = }") g() g() g()
12th Feb 2023, 9:46 PM
Per Bratthammar
Per Bratthammar - avatar