Code Explanation:
1. Defining the Outer Function
def outer(lst=[]):
A function named outer is defined.
It has a parameter lst with a default value of an empty list [].
This default list is created once at function definition time, not each time outer() is called.
2. Defining the Inner Function
def inner():
lst.append(len(lst))
return lst
inner is defined inside outer.
It captures lst from the enclosing scope (closure).
Each call:
Appends the current length of lst to lst.
Returns the modified list.
3. Returning the Inner Function
return inner
outer returns the function inner.
The returned function keeps a reference to the same lst.
4. Creating Two Functions
f = outer()
g = outer()
outer() is called twice.
But since lst is a shared default argument, both f and g refer to the same list object.
So:
f.lst → same list
g.lst → same list
5. Calling the Functions
print(f(), g())
Let’s evaluate:
▶ f():
Initial lst = []
len(lst) = 0 → append 0
lst = [0]
Returns [0]
▶ g():
Uses the same list
Now lst = [0]
len(lst) = 1 → append 1
lst = [0, 1]
Returns [0, 1]
6. Final Output
[0] [0, 1]
Final Answer
✔ Output:
[0] [0, 1]


0 Comments:
Post a Comment