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
2 Respuestas
+ 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.
+ 1
Thank yo so much