1

Might seems like a nooby question (myabe it is), but why does python behave like that:

>>>a = []
>>>for i in xrange(5):
...    a.append(lambda: i + 1)

>>>a[0]()
5
>>>a[1]()
5
>>>a[2]()
5
>>>a[3]()
5
>>>a[4]()
5

when there are different functions stored in a:

>>aaa
[<function <lambda> at 0x100499d70>, <function <lambda> at 0x100499e60>, <function <lambda> at 0x100499ed8>, <function <lambda> at 0x100499de8>, <function <lambda> at 0x10049f050>]

or have I missed something really important in python docs?

0

1 Answer 1

6

the closure is built on the value of i which ends up as 4.

if you want to keep i inside lambda you can use default variables.

>>>for i in xrange(5):
...    a.append(lambda x=i: x + 1)
Sign up to request clarification or add additional context in comments.

1 Comment

exactly what I was looking for. All in all I was right about missing something important (time of execution and name spacing). Default arguments do store value in function name space. Thanks!

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.