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?

Sergey Aganezov jr
  • 675
  • 10
  • 18

1 Answers1

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)
thkang
  • 11,215
  • 14
  • 67
  • 83
  • 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! – Sergey Aganezov jr Apr 24 '13 at 13:33