dugres
dugres

Reputation: 13085

Why would you use lambda instead of def?

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.

Upvotes: 0

Views: 853

Answers (5)

Dave Kirby
Dave Kirby

Reputation: 26552

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.

Upvotes: 1

Daren Thomas
Daren Thomas

Reputation: 70314

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.

Upvotes: 0

kgiannakakis
kgiannakakis

Reputation: 104178

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.

Upvotes: 1

David Webb
David Webb

Reputation: 193696

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))

Upvotes: 2

Philipp
Philipp

Reputation: 49802

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

Upvotes: 4

Related Questions