Python create list of function pointers to be called later specifying arguments at creation

Question:

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.

Asked By: Jan-Loettgen

||

Answers:

You need to pass i as an argument in lambda funcion

fun_list = [lambda x=i: foo(x) for i in range(5)]
Answered By: Nejc
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.