Code Explanation:
1. Global Variable Definition
x = 10
A global variable x is created.
Value of x is 10.
This variable is accessible outside functions.
2. Function Definition (outer)
def outer():
A function named outer is defined.
No code runs at this point.
Function execution starts only when called.
3. Local Variable Inside Function
x = 5
A local variable x is created inside outer.
This shadows the global x.
This x exists only within outer().
4. Lambda Function and Closure
return map(lambda y: y + x, range(3))
range(3) produces values: 0, 1, 2
The lambda function:
Uses variable x
Captures x from outer’s local scope
This behavior is called a closure
map() is lazy, so no calculation happens yet.
A map object is returned.
5. Global Variable Reassignment
x = 20
The global x is updated from 10 to 20.
This does not affect the lambda inside outer.
Closures remember their own scope, not global changes.
6. Function Call and Map Evaluation
result = list(outer())
outer() is called.
Inside outer():
x = 5 is used
list() forces map() execution:
y Calculation Result
0 0 + 5 5
1 1 + 5 6
2 2 + 5 7
Final list becomes:
[5, 6, 7]
7. Output
print(result)
Output:
[5, 6, 7]


0 Comments:
Post a Comment