[Tutor] Lamdas and locality
Kent Johnson
kent37 at tds.net
Sat Mar 3 23:12:18 CET 2007
Michael Meier wrote:
> Hello
>
> I ran the following code in python:
>
>>>> ls = [(lambda op: op + i) for i in [1,2,3]]
>>>> ls
> [<function <lambda> at 0xb7de4cdc>, <function <lambda> at 0xb7de4d14>,
> <function <lambda> at 0xb7de4d4c>]
>>>> for l in ls:
> ... print l(5)
> ...
> 8
> 8
> 8
>>>>
>
>
> I am quite surprised of the result. I'm generating three lamdas. What I
> want to do is that the first lamda adds 1 to the operand and returns it,
> the second lamda return 2 plus the operand and so on.
> However all the three lamdas, despite being not the same object in
> memory, are all adding 3, so they've got to have a reference to and not
> to 1,2,3 respectively.
>
> Why are the lamdas having a reference to the same integer? What am I
> getting wrong here? :P
This behaviour surprises many people. The lambda does not bind the value
of i. When you execute the lambda it looks up the value of i in the
enclosing scope which in this case is the global namespace. Each
function will get the same value because they all look up i in the same
place.
As a workaround you can bind the value of i to a default argument like this:
In [1]: ls = [(lambda op, i=i: op + i) for i in [1,2,3]]
In [2]: for f in ls:
...: print f(5)
...:
6
7
8
Kent
PS When you reply to an archive please delete the parts of the archive
that are not of interest.
More information about the Tutor
mailing list