[Tutor] List comprehension + lambdas - strange behaviour

spir ☣ denis.spir at gmail.com
Thu May 6 22:27:43 CEST 2010


On Thu, 06 May 2010 16:53:07 -0300
Ricardo Aráoz <ricaraoz at gmail.com> wrote:

> So you see, your functions just return the value of x. That's because
> the lambda have no parameter, so x refers to the global name x.

In other words, the "upvalue" (the variable captured in the closure) is referenced. Meaning if you later change it, the closure sees the change. The same in other dynamic languages.
If you want the value to be captured in each func, use a second lambda to pass it:
>>> funcs = [(lambda a: (lambda: a))(x) for x in range(5)]
>>> [f() for f in funcs]
[0, 1, 2, 3, 4]

Or even ;-):
>>> [(lambda a: (lambda: a))(x)() for x in range(5)]
[0, 1, 2, 3, 4]

... but --> KISS principle http://en.wikipedia.org/wiki/Keep_it_simple_stupid
Such syntaxes are only good for creating problems, imo. Why not make your life simple? (exception: for exploring the language's guts)

Denis
________________________________

vit esse estrany ☣

spir.wikidot.com


More information about the Tutor mailing list