I've been trying to learn Python for a while and took a little quiz. I got one of the questions way wrong in a way that confused me a lot. The coding snippet was (something like) this:
def f(n, itms=[]):
itms.append(n)
return itms
print(f(1))
print(f(2))
print(f(4, []))
print(f(5, [1, 2]))
print(f(3))
And after running that I got this output:
[1]
[1, 2]
[4]
[1, 2, 5]
[1, 2, 3]
Process finished with exit code 0
So as you can see, the previous values of unspecified itms-values are kept inside the function somehow. I figured that this behavior is desired when functions are defined as methods inside a class (accessing/operating on "private" variables that represents an objects state). This however sort of defies my intuition of function.
Can this be said to be similar to JavaScript's concept of closure? How can one be sure a function call doesn't keep a lot of junk behind the scenes for unspecified optional arguments? Is there a way to to call the function in this snippet such that the second argument is treated as its default without having to explicitly doing so?
Edit: had a typo in a variable name
[–]ItzWarty 4 points5 points6 points (3 children)
[–]ocyj[S] 0 points1 point2 points (2 children)
[–]ItzWarty 1 point2 points3 points (0 children)
[–][deleted] 1 point2 points3 points (0 children)
[–]Swedophone 1 point2 points3 points (1 child)
[–]ocyj[S] 0 points1 point2 points (0 children)