+9

Why is the difference in result

Among the tests there is such a question. def f(q, my list =[]): mylist = mylist + q return mylist a = [1] print(f(a)) a = [2] print(f(a)) >>>[1] [2] If we change the code, then the result changes: def f(q, my list =[]): mylist += q return mylist a = [1] print(f(a)) a = [2] print(f(a)) >>>[1] [1, 2] and now what doesn't fit in my head: def f(q, my list =[]): print(mylist) mylist = mylist + q return mylist a = [1] f(a) a = [2] f(a) >>>[] [] And here is another result, and I don't understand this. After all, print goes on the first line and the result should be the same: def f(q, my list =[]): print(mylist) mylist += q return mylist a = [1] f(a) a = [2] f(a) >>>[] [1] Is this something that just needs to be taken as an axiom, or is there some kind of explanation?

9/12/2019 3:57:07 AM

Mikhail Gorchanyuk

2 Answers

New Answer

+5

It has to do with object instances. In the quiz question you are pointing to a new object when you reassign the default parameter. In your first modification, you are modifying the same object as the default parameter so the reference is preserved and the same operation is done.

+3