0

The easiest way to explain the problem is by showing the code:

def foo(stuff):
    print(stuff)

fun_list = [lambda :foo(i) for i in range(5)]

for fun in fun_list:
    fun()

When the functions are called they all print 4. I would like them to print the actual value of i from when they were created, so 0, 1, 2, 3, and 4. This is all part of a large multithreaded project, which I need to use this blueprint.

Michael M.
  • 10,486
  • 9
  • 18
  • 34

1 Answers1

-1

You need to pass i as an argument in lambda funcion

fun_list = [lambda x=i: foo(x) for i in range(5)]
Nejc
  • 220
  • 1
  • 8