1

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 unnamed function, but about lambda as a named function.

There is a good answer to the same question here.

Community
  • 1
  • 1
dugres
  • 12,613
  • 8
  • 46
  • 51

5 Answers5

4

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

Philipp
  • 48,066
  • 12
  • 84
  • 109
  • 1
    How about currying, and other common functional programming tasks? Yes, it makes functionalists happy. As they should, since it's one of the major branches of programmers. – Daniel Kats Apr 02 '12 at 18:34
2

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))
David Webb
  • 190,537
  • 57
  • 313
  • 299
  • 1
    `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 – John La Rooy Jul 20 '10 at 09:59
1

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
  • 103,016
  • 27
  • 158
  • 194
1

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
  • 25,806
  • 5
  • 67
  • 84
0

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
  • 67,947
  • 40
  • 154
  • 200