Re: List comprehension + lambdas - strange behaviour

2010-05-07 Thread Terry Reedy
On 5/7/2010 8:31 AM, Neil Cerutti wrote: On 2010-05-07, Terry Reedy wrote: On 5/6/2010 3:34 PM, Artur Siekielski wrote: Hello. I found this strange behaviour of lambdas, closures and list comprehensions: funs = [lambda: x for x in range(5)] [f() for f in funs] [4, 4, 4, 4, 4] You succumbe

Re: List comprehension + lambdas - strange behaviour

2010-05-07 Thread Neil Cerutti
On 2010-05-07, Terry Reedy wrote: > On 5/6/2010 3:34 PM, Artur Siekielski wrote: >> Hello. >> I found this strange behaviour of lambdas, closures and list >> comprehensions: >> > funs = [lambda: x for x in range(5)] > [f() for f in funs] >> [4, 4, 4, 4, 4] > > You succumbed to lambda hypno

Re: List comprehension + lambdas - strange behaviour

2010-05-06 Thread Terry Reedy
On 5/6/2010 3:34 PM, Artur Siekielski wrote: Hello. I found this strange behaviour of lambdas, closures and list comprehensions: funs = [lambda: x for x in range(5)] [f() for f in funs] [4, 4, 4, 4, 4] You succumbed to lambda hypnosis, a common malady ;-). The above will not work in 3.x, whi

Re: List comprehension + lambdas - strange behaviour

2010-05-06 Thread Raymond Hettinger
On May 6, 9:34 pm, Artur Siekielski wrote: > Hello. > I found this strange behaviour of lambdas, closures and list > comprehensions: > > >>> funs = [lambda: x for x in range(5)] > >>> [f() for f in funs] > > [4, 4, 4, 4, 4] > > Of course I was expecting the list [0, 1, 2, 3, 4] as the result. The

Re: List comprehension + lambdas - strange behaviour

2010-05-06 Thread Benjamin Peterson
Artur Siekielski gmail.com> writes: > > Of course I was expecting the list [0, 1, 2, 3, 4] as the result. The > 'x' was bound to the final value of 'range(5)' expression for ALL > defined functions. Can you explain this? Is this only counterintuitive > example or an error in CPython? The former.

Re: List comprehension + lambdas - strange behaviour

2010-05-06 Thread Emile van Sebille
On 5/6/2010 12:34 PM Artur Siekielski said... Hello. I found this strange behaviour of lambdas, closures and list comprehensions: funs = [lambda: x for x in range(5)] funs is now a list of lambda functions that return 'x' (whatever it currently is from whereever it's accessible when invoked)

List comprehension + lambdas - strange behaviour

2010-05-06 Thread Artur Siekielski
Hello. I found this strange behaviour of lambdas, closures and list comprehensions: >>> funs = [lambda: x for x in range(5)] >>> [f() for f in funs] [4, 4, 4, 4, 4] Of course I was expecting the list [0, 1, 2, 3, 4] as the result. The 'x' was bound to the final value of 'range(5)' expression for