0

Python challenge results explanation

Dear All, I’m a new learner and have a results can’t understand by myself hope someone could help me out. What is the output for this code: def f(x=[]): x+=[1] return sum(x) Print(f()+f()+f()) Result is 6, I can’t understand why. Please help me. Thanks

27th Apr 2019, 2:44 PM
peter
2 Antworten
+ 3
def f(x=[]): x+=[1] return x print(f()) # [1] print(f()) # [1, 1] print(f()) # [1 ,1, 1] The list "x" is originally an empty list. In the first iteration a 1 gets added to it. For the second iteration, "x" is no longer empty, but is equal to [1] and the function returns [1, 1]. For the third iteration, "x" equals [1, 1] and the function returns [1, 1, 1]. Summing the values of the list in each iteration gives you (1) + (1+1) + (1+1+1) == 6.
27th Apr 2019, 2:56 PM
Diego
Diego - avatar
+ 1
Thank yo so much
27th Apr 2019, 3:08 PM
peter