When we create python functions, sometimes we do not need to define python functions explicitly, and it is more convenient to pass them into anonymous functions directly. This saves us the trouble of trying to name functions, and we can also write less code. Many programming languages provide this feature. The so-called anonymity means that a function is no longer defined in the standard form of def statement.
Python uses the lambda keyword to create anonymous functions. A lambda is just an expression, not a block of code, and the body of the function is much simpler than def. But only limited logic can be encapsulated in lambda expressions. And lambda functions have their own namespace. The form is usually something like this: lambda argument: expression.
For example: lambda x: x + x is equivalent to the following function. Keyword lambda represents anonymous function, x before colon represents function parameter, and x + x represents the executing code.
def sum(x): return x + x
Below is the summary of python anonymous function characteristics.
- An anonymous function can have only one expression, the return statement is not used or written, and the result of the expression is the anonymous function’s return value.
- Anonymous functions don’t have function names, so you don’t have to worry about function name collisions to save semantic space.
- Anonymous function is also a function object. You can assign anonymous function to a variable, and then call the function by using the variable.
>>> sum = lambda x: x + x >>> sum <function <lambda> at 0x3216fef44> >>> sum(6) 12