Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

lambda in python reference mind puzzle

Consider this example

def dump(value):
    print value

items = []    
for i in range(0, 2):
    items.append(lambda: dump(i))

for item in items:
    item()

output:

1
1

how can i get:

0
1
like image 322
Bojan Radojevic Avatar asked Oct 11 '12 12:10

Bojan Radojevic


3 Answers

You can use a parameter with a default value on the lambda:

for i in range(0, 2):
    items.append(lambda i=i: dump(i))

This works because the default value is evaluated when the function is defined, not when it is called.

like image 155
Mark Byers Avatar answered Nov 20 '22 13:11

Mark Byers


You can use:

for i in range(0, 2):
    items.append(lambda i=i: dump(i))

to capture the current value of i

This works because default parameter values are evaluated at function creation time, and i is not the external variable, but a function parameter that will have the value you want as default.

A more detailed explanation can be found in this answer.

like image 34
Paolo Moretti Avatar answered Nov 20 '22 14:11

Paolo Moretti


For completeness, you can also do:

for i in range(0, 2):
    items.append((lambda i: lambda: dump(i))(i))
like image 41
newacct Avatar answered Nov 20 '22 15:11

newacct