Asked By – Ray
I mostly use lambda functions but sometimes use nested functions that seem to provide the same behavior.
Here are some trivial examples where they functionally do the same thing if either were found within another function:
>>> a = lambda x : 1 + x >>> a(5) 6
>>> def b(x): return 1 + x >>> b(5) 6
Are there advantages to using one over the other? (Performance? Readability? Limitations? Consistency? etc.)
Does it even matter? If it doesn’t then does that violate the Pythonic principle:
There should be one– and preferably only one –obvious way to do it..
Now we will see solution for issue: Which is more preferable to use: lambda functions or nested functions (‘def’)?
If you need to assign the
lambda to a name, use a
defs are just syntactic sugar for an assignment, so the result is the same, and they are a lot more flexible and readable.
lambdas can be used for use once, throw away functions which won’t have a name.
However, this use case is very rare. You rarely need to pass around unnamed function objects.
filter() need function objects, but list comprehensions and generator expressions are generally more readable than those functions and can cover all use cases, without the need of lambdas.
For the cases you really need a small function object, you should use the
operator module functions, like
operator.add instead of
lambda x, y: x + y
If you still need some
lambda not covered, you might consider writing a
def, just to be more readable. If the function is more complex than the ones at
operator module, a
def is probably better.
So, real world good
lambda use cases are very rare.
This question is answered By – nosklo
This answer is collected from stackoverflow and reviewed by FixPython community admins, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0