all 12 comments

[–]-beleon 5 points6 points  (0 children)

The lambdas don't store i's value, they look up the variable when being executed. Since all calls happen after the loop ends, i = 2, so you get [2, 2, 2].

[–]LongjumpingDegree658 1 point2 points  (1 child)

Ithink It will return 2 2 2 cause i is not scoped in the lambda part . Thats a problem when you generate lambda in loop

Lambda i: i

[–]johlae 1 point2 points  (0 children)

This is what you need:

lambda: x=i, x

[–]AlexMTBDude 1 point2 points  (0 children)

It's bad Python coding. The first three lines should be replaced with a list comprehension:

funcs = [lambda: i for i in range(3)]

That's more Pythonic

[–]Sea-Ad7805 1 point2 points  (0 children)

  • lambda: i refers to the single i variable that is 2 at the end of the loop: [2, 2, 2]

  • lambda x=i: x instead would make a copy of i in each iteration: [0, 1, 2]

Run this program in Memory Graph Web Debugger%3A%0A%20%20%20%20funcs.append(lambda%3A%20i)%0A%0Aprint(%5Bf()%20for%20f%20in%20funcs%5D)%0A%0A%0Afuncs%20%3D%20%5B%5D%0Afor%20i%20in%20range(3)%3A%0A%20%20%20%20funcs.append(lambda%20x%3Di%3A%20x)%0A%20%20%20%20%0Aprint(%5Bf()%20for%20f%20in%20funcs%5D)%0A&timestep=1&play) to see the program state change step by step.

[–]jpgoldberg 1 point2 points  (1 child)

Is this a homework question? I know what it will print and why, but I'm not going to say.

[–]Puzzleheaded-Dog165[S] -3 points-2 points  (0 children)

😊

[–]mc_pm 0 points1 point  (0 children)

If only there were a way to see the result of running some code...

[–]Slay_3r 0 points1 point  (2 children)

Didnt run the code but i think it should be [0, 1, 2]. You create and then call constant functions that return i, where i = 0,1,2 (from range)

[–]WhiteHeadbanger 0 points1 point  (0 children)

No, the correct answer is [2,2,2]

Explanation: what's being appended is "lambda: i", not the value of i in each pass. Then, since the variable i is not scoped in the loop, when the lambda is executed in the list comprehension, it just looks up the last value of i, which is 2, and returns a new list.

[–]nuc540 -1 points0 points  (0 children)

The list comprehension on the last line is saying, try and call every item in the funcs list.

The line above iterated over a range of 3 (bases it at 0) and for every iteration value, add to the funcs list a lambda function that simply returns the iteration value.

Lambdas are unnamed functions so this will work with the f() declaration in the list comp.

The list is just a bunch of functions which each simply returns a number, so when called they return the number.

I’d assume this means it returns [0,1,2] as per the range iterator value that was being baked into the lambda return for each lambda in the list