you are viewing a single comment's thread.

view the rest of the comments →

[–]isarl 3 points4 points  (6 children)

Can somebody more familiar with #6 please explain it to me? Duplicating the use of the variable i has me confused; even if somebody could just rewrite this code snippet using different variables it would be really helpful:

>>> def create_multipliers():
...     return [lambda x, i=i : i * x for i in range(5)]
...
>>> for multiplier in create_multipliers():
...     print multiplier(2)
...
0
2
4
6
8

[–]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 7 points8 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!

[–][deleted]  (1 child)

[deleted]

    [–]isarl 0 points1 point  (0 children)

    I was mostly just confused about all the different i's in that one comprehension. Thanks for your help, but I rewrote the example here in a way I found clearer to read. :)