You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
+[▶ Methods equality and identity](#-methods-equality-and-identity)
@@ -989,10 +989,9 @@ We can avoid this scenario here by not using `row` variable to generate `board`.
989
989
990
990
---
991
991
992
-
### ▶ The sticky output function
992
+
### ▶ Schrödinger's variable *
993
993
<!-- Example ID: 4dc42f77-94cb-4eb5-a120-8203d3ed7604--->
994
994
995
-
1\.
996
995
997
996
```py
998
997
funcs = []
@@ -1006,45 +1005,63 @@ for x in range(7):
1006
1005
funcs_results = [func() for func in funcs]
1007
1006
```
1008
1007
1009
-
**Output:**
1010
-
1008
+
**Output (Python version):**
1011
1009
```py
1012
1010
>>> results
1013
1011
[0, 1, 2, 3, 4, 5, 6]
1014
1012
>>> funcs_results
1015
1013
[6, 6, 6, 6, 6, 6, 6]
1016
1014
```
1017
-
Even when the values of `x` were different in every iteration prior to appending `some_func` to `funcs`, all the functions return6.
1018
1015
1019
-
2\.
1016
+
The values of `x` were different in every iteration prior to appending `some_func` to `funcs`, but all the functions return6 when they're evaluated after the loop completes.
1017
+
1018
+
2.
1020
1019
1021
1020
```py
1022
1021
>>> powers_of_x = [lambdax: x**i for i inrange(10)]
* When defining a function inside a loop that uses the loop variable in its body, the loop function's closure is bound to the *variable*, not its *value*. The function looks up `x` in the surrounding context, rather than using the value of `x` at the time the function is created. So all of the functions use the latest value assigned to the variable for computation. We can see that it's using the `x`from the surrounding context (i.e. *not* a local variable) with:
Since `x`is a global value, we can change the value that the `funcs` will lookup andreturn by updating `x`:
1028
1034
1029
-
- When defining a function inside a loop that uses the loop variable in its body, the loop function's closure is bound to the variable, not its value. So all of the functions use the latest value assigned to the variable for computation.
1035
+
```py
1036
+
>>> x = 42
1037
+
>>> [func() for func in funcs]
1038
+
[42, 42, 42, 42, 42, 42, 42]
1039
+
```
1030
1040
1031
-
- To get the desired behavior you can passin the loop variable as a named variable to the function. **Why does this work?** Because this will define the variable
1032
-
within the function's scope.
1041
+
* To get the desired behavior you can passin the loop variable as a named variable to the function. **Why does this work?** Because this will define the variable *inside* the function's scope. It will no longer go to the surrounding (global) scope to look up the variables value but will create a local variable that stores the value of `x` at that point in time.
0 commit comments