A detailed description of the lambda expression usage in Python

Source: Internet
Author: User
Tags python list
The examples in this article describe the use of lambda expressions in Python. Share to everyone for your reference, as follows:

Here to introduce you to the lambda function.

A lambda function is a minimal function that quickly defines a single line, borrowed from Lisp and can be used wherever a function is needed. The following example compares the traditional function definition def with the lambda definition:

>>> def f (x, y): ...   return x * y...>>> f (2,3) 6>>> g = lambda x, y:x * y>>> g (2,3) 6

As you can see, the two functions get the same results, and for functions that implement simple functions, the use of a lambda function to define more streamlined and flexible, you can also directly assign a function to a variable, the variable name to represent the function name.

In fact, lambda functions do not need to be assigned to a variable in many cases.

There are a few caveats to using the lambda function: The lambda function can receive any number of arguments (including optional parameters) and return the value of a single expression. A lambda function cannot contain commands and cannot contain more than one expression .

Here's a quick example of how to use a lambda function to implement a custom sort.

Class people: Age  = 0  gender = "Male"  def __init__ (self, Age, gender): self    .    Ender = Gender  def toString (self):    return ' Age: ' + str (self. Age) + '/t Gender: ' + ' self. Genderlist = [P  Eople (+, ' male '), people (+, ' famale '), people ("male"), people (+, ' famale ')]print ' Befor sort: ' For P In list:  print P. toString () list. Sort (lambda P1, p2:cmp (P1. Age, P2. Age)) print '/n after ascending Sort: ' For P in list:  print P. toString () list. Sort (lambda p1, P2:-CMP (P1. Age, P2. Age)) print '/n Aft Er descending sort: ' for P in List:  print P. toString ()

The above code defines a people class and, through a lambda function, implements a list of objects containing people classes in ascending and descending order, according to the age of people. The results of the operation are as follows:

Befor Sort:
Age:21 Gender:male
Age:20 Gender:famale
Age:34 Gender:male
Age:19 Gender:famale
After ascending sort:
Age:19 Gender:famale
Age:20 Gender:famale
Age:21 Gender:male
Age:34 Gender:male
After descending sort:
Age:34 Gender:male
Age:21 Gender:male
Age:20 Gender:famale
Age:19 Gender:famale

Lambda statements are used to create new function objects and return them at run time.

Example: Using lambda form

#!/usr/bin/python# Filename:lambda.pydefmake_repeater (n):  return lambda s:s*ntwice = Make_repeater (2) print twice (' word ') print twice (5)

Output:

$ python Lambda.pywordword10

How it works

Here, we use the Make_repeater function to create a new function object at run time and return it.

A lambda statement is used to create a function object. Essentially, a lambda requires a parameter, followed only by a single expression as the body of the function, and the value of the expression is returned by the new function. Note that even the print statement cannot be used in lambda form, only expressions are used.

The difference between def and Lambda

The main difference is that Python def is a statement and Python lambda is an expression, and it's important to understand them. Let's take a look at their application.
First, in Python, the statements can be nested, for example, you need to define a method according to a condition, it can only use def.

You'll get an error with your lambda.

A = 2if a > 1:  def info ():    print ' haha ' else:  def test ():    print ' Test '

And sometimes when you need to work in a Python expression, you need to use an expression nesting, and this time Python def can't get the result you want, it can only be used with Python lambda

Here's an example:

G = lambda X:x+2info = [g (x) for x in range (]print info)

In the example above, I hope you can understand the same and different points of Python def and Lambda very well. If you are interested in Python functions, you can look at: Python function return value, Python function parameter

Python lambda is using lambda in Python to create anonymous functions, and the method created with Def is named, but what else does Python lambda have to do with Def, in addition to the method names on the surface?

①python Lambda creates a function object, but does not assign the function object to an identifier, and Def assigns the function object to a variable.

②python Lambda It's just an expression, and DEF is a statement.

The following is a Python lambda format that looks good and streamlined.

Lambda X:print x

If you use Python lambda in the Python list parsing, I don't feel much of a thing because Python lambda creates a function object, but discards it immediately, because you're not using its return value, which is the function object. It is also because Lambda is just an expression that can be directly a member of a Python list or a Python dictionary, such as:

info = [Lamba a:a**3, Lambda B:b**3]

There is no way to replace the DEF statement directly in this place. Because DEF is a statement, not an expression that cannot be nested inside, a lambda expression can have only one expression after ":". That is, in Def, return can also be placed behind a lambda, and cannot be returned with return can not be defined behind a Python lambda. Therefore, a statement such as if or for or print cannot be used in a lambda, and lambda is generally used only to define simple functions.

Let's give some examples of Python lambda.

① for single parameters:

g = Lambda X:x*2print g (3)

The result is 6.

② for multiple parameters:

m = lambda x, y, Z: (x-y) *zprint m (3,1,2)

The result is 4.

It's fine to use Python lambda when writing programs.

More interested in Python related content readers can view this site topic: "Python Picture Operation skills Summary", "Python data structure and algorithm tutorial", "Python Socket Programming Skills Summary", "Python function Use Tips", " Python string manipulation Tips Summary, Python Introductory and Advanced classic tutorials, and Python file and directory operations tips

I hope this article is helpful for Python program design.

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