0

the following code:

tab = [lambda: elt for elt in [1,2,3,4,5]]
for elt in tab:
        print(elt())

gives the following output:

➜  ~ python code.py
5
5
5
5
5

Is there any way to switch off (or weaken) this optimisation?

JosephConrad
  • 678
  • 2
  • 9
  • 20
  • Also find this additional [blog post](https://docs.python-guide.org/writing/gotchas/#late-binding-closures) which I find it useful to understand what's happening here. – Abdul Niyas P M Sep 07 '21 at 12:39
  • 1
    It's not an optimisation; it's just the way Python variables work. – khelwood Sep 07 '21 at 12:43
  • 1
    This definition of tab produces the desired output: `tab = [lambda x=elt: x for elt in [1,2,3,4,5]]` (i.e. lambda function with default argument). This way we get a closure on each of the values as desired. – DarrylG Sep 07 '21 at 12:46
  • ok, thanks all clear now! – JosephConrad Sep 07 '21 at 12:52

0 Answers0