0

The following program should print 3 if 0 is given as argument but prints 6.

Not sure if the problem lies in the lambda function or whether the logic is incorrect. Is it the lambda function that is incorrect? Thank you.

def get_list_sum(p, func_list=None):
    if func_list is None:
        func_list = []

    for i in range(3):
        func_list.append(lambda x: x + i)

    s = 0
    for func in func_list:
        s += func_list(p)

    return s
Adam Strauss
  • 1,889
  • 2
  • 15
  • 45
jn009
  • 11
  • 2
  • can you give some input and expected output pairs? I don't see anywhere that you're printing – IanQ Feb 19 '20 at 05:23
  • I'm getting *"list object is not callable"*, not 6. – Austin Feb 19 '20 at 05:23
  • 3
    Probably meant `s += func(p)` in the example. – Mark Feb 19 '20 at 05:25
  • It looks reasonable of your output – Zhubei Federer Feb 19 '20 at 05:26
  • 2
    By the time you call the functions, `i` is already 2, for all calls. If you want to current value of `i` you need to capture it with something like: `func_list.append(lambda x, i=i: x + i)` Perhaps [this](https://stackoverflow.com/questions/2295290/what-do-lambda-function-closures-capture) is the canonical answer to this issue? – Mark Feb 19 '20 at 05:28

0 Answers0