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

Do you mind fleshing out your example with some actual code? I'm not quite following, and I'm completely lost by the time you talk about the workaround.



Sure, what I meant by the "obvious" way of making some polynomials is:

    polys = []
    for i in range(0,4):
        polys.append(lambda x: x**i)
But that actually just yields the same polynomial x -> x^3 in each element of polys array:

    polys[0](2)
    > 8
    polys[1](2)
    > 8
    polys[2](2)
    > 8
The same thing happens if we use a list comprehension:

    polys = [lambda x: x**i for i in range(0,4)]
The trick is to add a default argument value to the lambda, which catches "i" by value instead of by reference:

    for i in range(0,4):
        polys.append(lambda x, i=i: x**i)
    
And now we get the different polynomials we expected:

    polys[0](2)
    > 1
    polys[1](2)
    > 2
    polys[2](2)
    > 4
    polys[3](2)
    > 8




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

Search: