Code Explanation:
1. Defining the Outer Function
def outer():
A function named outer is defined.
It will create and return another function.
2. Creating a Mutable Variable
x = []
A list named x is created inside outer.
This list will be shared by the inner function through a closure.
3. Defining the Inner Function
def inner():
x.append(len(x))
return x
inner is defined inside outer, so it captures x from the outer scope.
Every call to inner:
Computes len(x) (current length of the list),
Appends that value to x,
Returns the updated list.
4. Returning the Inner Function
return inner
outer returns the inner function.
The returned function still has access to the list x because of the closure.
5. Creating the Closure
f = outer()
outer() is called once.
A new list x = [] is created.
inner is returned and assigned to f.
f now remembers and shares the same x across all calls.
6. Calling the Function Multiple Times
print(f(), f(), f())
Let’s evaluate each call:
▶ First f():
x = []
len(x) = 0, append 0 → x = [0]
Returns [0]
▶ Second f():
x = [0]
len(x) = 1, append 1 → x = [0, 1]
Returns [0, 1]
▶ Third f():
x = [0, 1]
len(x) = 2, append 2 → x = [0, 1, 2]
Returns [0, 1, 2]
7. Final Output
[0] [0, 1] [0, 1, 2]
Final Answer
✔ Output:
[0] [0, 1] [0, 1, 2]


0 Comments:
Post a Comment