tags:

views:

142

answers:

5

Is there any reason that will make you use:

add2 = lambda n: n+2

instead of :

def add2(n): return n+2

I tend to prefer the DEF way but every now and then I see the LAMBDA way being used.

EDIT :
The question is not about lambda as unamed function, but about lambda as NAMED function.

There is a good answer to the same question here.

+1  A: 

Guido Van Rossum (the creator of Python) prefers def over lambdas (lambdas only made it to Python 3.0 at the last moment) and there is nothing you can't do with def that you can do with lambdas.

People who like the functional programming paradigm seem to prefer them. Some times using an anonymous function (that you can create with a lambda expression) gives more readable code.

kgiannakakis
+3  A: 

lambda is nice for small, unnamed functions but in this case it would serve no purpose other than make functionalists happy.

Philipp
+1  A: 

I usually use a lambda for throwaway functions I'm going to use only in one place, for example as an argument to a function. This keeps the logic together and avoids filling the namespace with function names I don't need.

For example, I think

map(lambda x: x * 2,xrange(1,10))

is neater than:

def bytwo(x):
    return x * 2

map(bytwo,xrange(1,10))
Dave Webb
`lambda` has been in Python much much longer than list comprehensions, etc. The equivalent `[ x*2 for x in xrange(1,10) ]` runs faster than the map, so many places where `lambda` was a good solution are falling from favour
gnibbler
A: 

One place you can't use def is in expressions: A def is a statement. So that is about the only place I'd use lambda.

Daren Thomas
+1  A: 

I recall David Mertz writing that he preferred to use the form add2 = lambda n: n+2 because it emphasised that add2 is a pure function that has no side effects. However I think 99% of Python programmers would use the def statement and only use lambda for anonymous functions, since that is what it is intended for.

Dave Kirby