-1

I've created lambda functions from string expressions using eval, which worked fine. But when I try to apply it to a list, it always just uses the last function to evaluate the solution:

fun_name = ['x', '2*x']

fun_list = []

for f_str in fun_name:
    l_e = lambda x: eval(f_str)
    fun_list.append(l_e)

I create a list of expressions fun_name, an empty list fun_list, which will contain the lambda functions, and then iterate over all entries to create the lambda functions and add them to the list.

But when I try to call the functions they are all using just the last list-entry (or all entries are overwritten):

print(fun_list[0](12))
print(fun_list[1](12)) 

Instead of 12 and 24, both are returning:

24
24

Why is it that way and how can I fix this? I've searched but unfortunately found nothing alike here. I appreciate all ideas!

0 Answers0