The usage of lambda in Python and the difference between it and def are resolved

  • 2020-04-02 13:52:18
  • OfStack

Lambda in python is usually used to create anonymous functions in python, while methods created with def have names. In addition to the superficial method names, lambda in python differs from def in the following aspects:

1. Python lambda creates a function object but does not assign the function object to an identifier, while def assigns the function object to a variable.

Python lambda is just an expression, while def is a statement.

Here is the python lambda format, which looks very compact.


lambda x: print x

If you use a python lambda in python list parsing, it doesn't make a lot of sense, because python lambda creates a function object and then it's thrown away because you didn't use its return value, which is the function object. Because lambda is just an expression, it can be directly used as a member of a python list or python dictionary, such as:


info = [lamba a: a**3, lambda b: b**3]

There is no way to replace this with a def statement. Because def is a statement, not an expression, which cannot be nested inside, lambda expressions can only have one expression after ":". That is, in def, what can be returned with return can also be placed after a lambda, and what cannot be returned with return cannot be defined after a python lambda. Therefore, statements like if or for or print cannot be used in lambda, which is typically used to define simple functions.

Here are some examples of python lambda:

1. Case of a single parameter:


g = lambda x*2
print g(3)

The result is 6

2. Multiple parameters:


m = lambda x,y,z: (x-y)*z
print m(3,1,2)

The result is 4


Related articles: