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:
Lambda function
>>> a = lambda x : 1 + x >>> a(5) 6
Nested function
>>> 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..
If you need to assign the
lambdato a name, use adefinstead.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.
The builtins
map()andfilter()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
operatormodule functions, likeoperator.addinstead oflambda x, y: x + yIf you still need some
lambdanot covered, you might consider writing adef, just to be more readable. If the function is more complex than the ones atoperatormodule, adefis probably better.So, real world good
lambdause cases are very rare.