+ 1

Python: question about function on list

Hi, everybody! I have trouble understanding the output of the following code in Python: def func(a, L= []) L.append(a) return L print (func(1), func(3)) Why is the output [1,3][1,3] and not [1][1,3]? Please help.

19th Jun 2019, 5:54 AM
Marek Kluczewski
Marek Kluczewski - avatar
5 Answers
+ 4
Each function call changes the default parameter L. After the first call, L will be [1]. The second call changes it to [1, 3]. print() only happens after the function was called twice
19th Jun 2019, 6:00 AM
Anna
Anna - avatar
+ 4
Maybe this code helps: https://code.sololearn.com/cvtllrZS8lrA/?ref=app f() is called twice from within print (). You'll see that the function first does its job two times in a row and only then are the return values handled (also two times in a row). This is because of the chained function calls in print(). It's a bit like a recursive function. Your code does the same. The function is called twice and both function calls change the value of L. After this happened, the value of L is printed. By the time this happens, L has already been changed twice.
19th Jun 2019, 6:49 AM
Anna
Anna - avatar
+ 1
Why does print() happen only after the function is called twice? I really don't get this one. What happens exactly? Step 1. func (1) -> L =[1] Step 2. func (3) -> L = [1,3] I understand the code and the output until this moment. But why is [1,3][1,3] finally printed, I don't understand. Is there step 3 hidden somewhere?
19th Jun 2019, 6:21 AM
Marek Kluczewski
Marek Kluczewski - avatar
+ 1
After both functions in print() are run, you can read that line as print(L , L) and at that point L = [1,3].
19th Jun 2019, 7:01 AM
kawelo
kawelo - avatar
+ 1
Summing up, in this case first both functions are called and L becomes [1,3]. Printing is done only after all functions are run in the print function. Is this correct?
19th Jun 2019, 7:04 AM
Marek Kluczewski
Marek Kluczewski - avatar