Python Learning note __4.3 anonymous function (concise function)

Source: Internet
Author: User

# This is a learning note for the Liaoche teacher Python tutorial

1. Overview

The keyword lambda represents an anonymous function

List (map (lambda x:x * x, [1, 2, 3, 4, 5, 6, 7, 8, 9]))

# The Lambda in the list-building is actually

def f (x):

return x * x

But there is a limit to anonymous functions, that is, there can only be one expression.

Anonymous function does not write return, the return value is the result of the expression

anonymous function because the function has no name, you do not have to worry about the function name conflict.

In addition, the anonymous function is also a function object, You can assign the anonymous function to a variable, and then use the variable to invoke the function, you can also return the anonymous function as a return value

# Anonymous function Assignment variable

>>> f = Lambda x:x * x

>>> F

<function <lambda> at 0x101c6ef28>

>>> F (5)

25

# anonymous function returned as return value

def build (x, y):

return lambda:x * x + y * y

2 , examples

1. Change the following function to anonymous function

#-*-Coding:utf-8-*-

def is_odd (n):

return n% 2 = = 1

L = List (filter (is_odd, Range (1, 20)))

Print (L)

# change

L = List (filter (lambda x:x%2==1, range (1, 20)))


Python Learning note __4.3 anonymous function (concise function)

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.