-2

This code demonstrates the problem well:

ans = []
for  x in range(1,10):
    ans.append(lambda: x)
# -----------------------
# now see what happened:
ans[0]()
# prints 9, but should print 1

What is the best way to have x be captured immediately in the function, rather than updating with the variable x later?

Mondo Duke
  • 185
  • 8
  • *why* do you want to do this? What is the problem, and what are you trying to solve? – rv.kvetch May 26 '22 at 02:09
  • 1
    https://stackoverflow.com/questions/10865116/tkinter-creating-buttons-in-for-loop-passing-command-arguments is an example of a common need for this, with a couple of solutions given. – jasonharper May 26 '22 at 02:23

1 Answers1

-3

I came up with this:

ans = []
for  x in range(1,10):
    ans.append(lambda *,x=x: x)

FYI x is declared as a global variable cuz python = dumb LOL!

Mondo Duke
  • 185
  • 8
  • 1
    but *why* did you come up with it? e.g. what is the point of having a list with seemingly useless lambdas in it? – rv.kvetch May 26 '22 at 02:11
  • glad you emphasized the word why, i wouldn't have known what u were asking for otherwise – Mondo Duke May 26 '22 at 02:22
  • x is not a global variable, so perhaps what is being said is dumb, rather than python itself for example. – rv.kvetch May 26 '22 at 02:25
  • is there a way to make x local to the for loop? – Mondo Duke May 26 '22 at 02:26
  • another thing is in case of `for x in range(0, 0)` - then `x` will never be defined, as loop doesn’t run. – rv.kvetch May 26 '22 at 02:27
  • that's true! :) – Mondo Duke May 26 '22 at 02:33
  • Your answer could be improved with additional supporting information. Please [edit] to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community May 26 '22 at 05:11