Difference between Python lambda and Python def, pythonlambda

Source: Internet
Author: User

Difference between Python lambda and Python def, pythonlambda

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

Lambda syntax is often confusing. What is lambda And why must lambda 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

Python def and Python lambda have similarities and differences.
Similarities: These two important similarities are that you can define some fixed methods or flows to be called by the program. For example, you can define a variable plus 2 in the preceding example. The output result is 3. If you want to complete some fixed procedures, you can choose any of the above.

Which of the following are the same points?
Their main difference is that Python def is a statement while Python lambda is an expression. Lambda simplifies the writing of function definitions and simplifies the code. However, the function definition method is more intuitive and easy to understand.

Statements in Python can be nested. For example, if you need to define a method based on a certain condition, you can only use def. If lambda is used, an error is reported.

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

Sometimes, when you need to operate in a python expression, you need to use expression nesting. In this case, Python def cannot get the desired result. You can only use Python lambda, as shown in the following example:
The most frequently-occurring letters of the Output e string:

>>> 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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.