Python lambda and Python def distinguish analysis

  • 2020-04-02 14:27:09
  • OfStack

Python supports an interesting syntax that allows you to quickly define the smallest function in a single line. These functions, called lambda, are borrowed from Lisp and can be used wherever functions are needed.

The syntax of lambda is often confusing. What is lambda, why is lambda used, and does lambda have to be used?


>>> def f(x):
...   return x+2
...
>>> f(1)
3
>>> f = lambda x:x+2
>>> f(1)
3
>>> (lambda x:x+2)(1)
3

There are similarities and differences between Python def and Python lambda.
Similarity: these two important similarities are that you can both define some fixed methods or processes that a program can call, such as the variable + 2 method defined in the above example. The output is 3, and you can choose any of the above if you want to complete some fixed process.

There are similarities. What are the differences?
The main difference is that Python def is a statement and Python lambda is an expression. Lambda simplifies the writing of function definitions and makes the code cleaner. But using a function definition is more intuitive and easy to understand.

In Python, statements can be nested, for example, if you need to define methods according to a certain condition, you can only use def. Lambda will give you an error.


>>> if a==1:
...   def info():
...     print '1'*5
... else:
...   def info2():
...     print 'info2'

While sometimes you need to operate in python expressions, which requires the use of nested expressions, at this time, python def can not get the result you want, which can only use python lambda, the following example:
Output e string with the highest frequency of letters:


>>> str='www.linuxeye.com linuxeye.com'
>>> L = ([(i,str.count(i)) for i in set(str)])
[(' ', 1), ('c', 2), ('e', 4), ('i', 2), ('m', 2), ('l', 2), ('o', 2), ('n', 2), ('u', 2), ('w', 3), ('y', 2), ('x', 2), ('.', 3)]
>>> L.sort(key = lambda k:k[1],reverse = True)
>>> print L[0][0]
e

Related articles: