+ 8
How does this code work?
It is giving output --- [1,3] https://code.sololearn.com/cUzxloWPiuyJ/?ref=app
4 odpowiedzi
+ 11
def func(x,y = []):
y.append(x)
return y
a = func(1)
b = func(2,[])
c = func(3)
print(c)
# output -----> [1,3]
__________
Above is your code.
Below is the line by line flow of the code.
That's how it works.
1-4-1-2-3-5
1-4-1-2-3-6
1-4-1-2-3-7
7- answer [1, 3 ]
end of file
+ 4
It involves the concept of default parameter and closure
y = [] in the parenthesis means if no second argument is passed into the function, the default is an empty list
At assignment of a, there is no second argument, so default parameter is triggered, an empty list of local scope is created and stores 1 and returned.
At assignment of b, the function is called with a second argument of [], so this new empty list of global scope is used to store 2 and returned.
Then at assignment of c, because there is no second argument again. The compiler looks for the the default parameter in its local scope first, and this time it FINDS it! variables in local scope is remembered. So it begins with being [1], so after 3 is appended. [1,3] is returned into c.
You can read more about closure here:
https://www.programiz.com/JUMP_LINK__&&__python__&&__JUMP_LINK-programming/closure
+ 4
See the answer from John Wells in this Q/A https://www.sololearn.com/Discuss/1017883/?ref=app
+ 1
I coded a demo about closure in Python.
https://code.sololearn.com/c9hXVLctBXzU/?ref=app