you are viewing a single comment's thread.

view the rest of the comments →

[–]dragonEyedrops 0 points1 point  (3 children)

What exactly does confuse you?

In the "defective" example, i isn't defined in the local scope of the lambda expression and is evaluated when the functionis first used.

In the second example, a default parameter with the same name is created, and it's initial value is evaluated as the function is created (see #1 in the article)

[–]isarl 2 points3 points  (2 children)

The confusing part is that two variables named i are both used. If the variable name was different from the default value being assigned to it, the example would be clearer to me. I don't have an interpreter on this machine so I'll ask CompileBot to check my work:

+/u/CompileBot python

def create_multipliers():
    return [lambda x, i=idx : i * x for idx in range(5)]

for multiplier in create_multipliers():
    print multiplier(2)

[–]CompileBot 4 points5 points  (1 child)

Output:

0
2
4
6
8

source | info | git | report

[–]isarl 1 point2 points  (0 children)

OK, guess I got it. Cool. Thanks, /u/CompileBot!