lambda forms within a loop
Duncan Booth
duncan.booth at invalid.invalid
Sun Oct 25 05:47:45 EDT 2009
Michal Ostrowski <mostrows at gmail.com> wrote:
> def MakeLambdaBad():
> a = []
> for x in [1,2]:
> a.append(lambda q: x + q)
> return a
Two things to remember when using lambda:
1. You can always replace lambda with one line function returning the same
result. The only difference is that you have to give the function a name.
I think using named functions is usually clearer because it makes the code
look a bit more visually distinct, not just part of some larger expression,
but YMMV.
So your code could have been written:
def MakeLambdaBad():
a = []
for x in [1,2]:
def baa(q): return x+q
a.append(baa)
return a
2. Except for argument defaults it is irrelevant where in a function the
lambda or def is executed: the code it contains is not evaluated until the
function is called.
So these are also the same as your original:
def MakeLambdaBad():
def baa(q): return x+q
a = []
for x in [1,2]:
a.append(baa)
return a
or if you prefer the lambda:
def MakeLambdaBad():
baa = lambda q: x+q
a = []
for x in [1,2]:
a.append(baa)
return a
or if you want the code a bit shorter:
def MakeLambdaBad():
def baa(q): return x+q
x = 2
return [baa, baa]
In case of pedants: when I say irrelevant I mean of course irrelevant so
long as the function has actually been defined before it is referenced.
More information about the Python-list
mailing list