Hacker News new | past | comments | ask | show | jobs | submit login

But you can do that in both python 3 and 2.5...



Maybe he's talking about

    >>> funcs = []
    >>> for x in xrange(3):
    >>>   funcs.append(lambda: x)
    >>> sum(f() for f in funcs)
    6
Were you expecting 3? Lambdas (besides having such an awfully long and difficult to type name :P) capture only the "name" of x, so when the for loop changes x later, the lambda sees the new value--so the sum is (2 + 2 + 2) instead of (1 + 2 + 3).

What you can do, instead (and I do it often enough that I wish lambdas created their own lexical closure....)

    >>> funcs = []
    >>> for x in xrange(3):
    >>>   funcs.append(lambda x=x: x)
    >>> sum(f() for f in funcs)
    3
By using x as a default argument, you force the x inside the lambda to be the value it was when the lambda was created. It kinda sucks, and always felt to me like a deficiency of the implementation leaking up into the language :[


I think you mean "2 + 2 + 2 instead of 0 + 1 + 2"




Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: