Python Lambda WTF

Status
You're currently viewing only kbogert's posts. Click here to go back to viewing the entire thread.
Not open for further replies.

kbogert

Smack-Fu Master, in training
77
Came across this today (code distilled down so I could post it):

Code:
t = []


for i in range(3):
        t.append(lambda : i)


t2  = []

def WTF(i):
        t2.append(lambda : i)


for i in range(3):
        WTF(i)


for x in t:
        print(x())

for x in t2:
        print(x())

This outputs:
Code:
2
2
2
0
1
2

WTF? It though the scope of the lambda is a snapshot of wherever it was created. Is there a way to get around this without having to add the function call?

Thanks in advance,
kdb
 
Status
You're currently viewing only kbogert's posts. Click here to go back to viewing the entire thread.
Not open for further replies.