def outer(l):
def inner(n):
return l * n
return inner
l = [1, 2, 3]
f = outer(l)
print(f(3)) # => [1, 2, 3, 1, 2, 3, 1, 2, 3]
l.append(4)
print(f(3)) # => [1, 2, 3, 4, 1, 2, 3, 4, 1, 2, 3, 4]
Because function outer
returns the function inner
, inner()
is now bound to the name f
. (f
is a closure)
When f()
is called, since l
can't be found in the local namespace, but can be found in the global namespace, l(=[1, 2, 3])
is passed to f()
.
The first f(3)
duplicates the list l
3 times, therefore, returns [1, 2, 3, 1, 2, 3, 1, 2, 3]
.
However, right before the second f(3)
, integer 4
is appended to the list l
. Now, l = [1, 2, 3, 4]
.
As a result, the second f(3)
duplicates the updated list l
3 times, therefore, returns [1, 2, 3, 4, 1, 2, 3, 4, 1, 2, 3, 4]
.
Am I correct? Or am I wrong?
Thank You.