Code Explanation:
1. Creating an Empty List
funcs = []
- Creates an empty list named funcs.
- This list will store multiple lambda functions.
- Each function will be added to this list using the append() method.
2. Starting the For Loop
for i in range(3):
- The range(3) function generates three values: 0, 1, and 2.
- The loop executes three times.
- During each iteration, the variable i receives the next value.
- These values will be accessed by the lambda functions.
3. Creating Lambda Functions
funcs.append(lambda: i)
- lambda creates an anonymous function without using the def keyword.
- This lambda function does not accept any arguments.
- It simply returns the current value of i when called.
- append() stores the newly created function inside the funcs list.
Important: The lambda functions do not immediately store the values 0, 1, and 2. They refer to the same variable i, which is looked up when the function is executed.
4. Calling the First Lambda Function
print(funcs[0]())
- funcs[0] accesses the first lambda function in the list.
- The additional () executes that function.
- By this time, the loop has completed.
- The final value of i is 2.
- Therefore, the function returns 2.
5. Calling the Second Lambda Function
print(funcs[1]())
- funcs[1] accesses the second lambda function.
- It also refers to the same variable i.
- Since the loop has already finished, i is still 2.
- Therefore, this function also returns 2.
6. Calling the Third Lambda Function
print(funcs[2]())
- funcs[2] accesses the third lambda function.
- It executes and reads the current value of i.
- The value of i remains 2.
- Therefore, it also returns 2.
Final Output
Correct Output
2
2
2


0 Comments:
Post a Comment