Python Anonymous Function: Lambda Function

Source: Internet
Author: User
Keywords python anonymous function lambda function
Anonymous function-one line function
lambda-keywords
x is a formal parameter (position, keyword...) of an ordinary function and may not receive parameters (x may not be written)
:x is the function value of an ordinary function (only one data type can be returned) (:x return value must be written)
1) This function is not without a name, he has a name, his name is called lambda
2) lambda is a keyword that defines an anonymous function, which is equivalent to the function's def.
3) Add formal parameters directly behind the lambda, as many shapes as you like, as long as they are separated by commas.
func = lambda a, b, *args, sex='alex', c, **kwargs: kwargs
print(func(3, 4, c=666, name='alex'))

Result: {'name':'alex'}
# All types of formal parameters can be added, but generally anonymous functions are used to add positional parameters, and others are not used.

Open the anonymous function and write as follows
def func(a, b, *args, sex='alex', c, **kwargs):
    return kwargs


a = func(3, 4, c=666, name='alex')
print(a)
Result: {'name':'alex'}

4) The return value is set after the colon. The return value is the same as the normal function and can be any data type. (But if you want to return multiple elements, return them in the form of a container)
5) No matter how complicated the anonymous function is. Only one line can be written. And the data is returned directly after the logic is over
Format: lambda x:x
print((lambda x: x + 6)(5))
Results: 11

def func(x):
return x + 6
print(func(5))
Results: 11

Use list comprehension here, the return value is the address
lst = [lambda :i for i in range(5)]
print(lst)

Disassemble into function:


lis = []
for i in range(5):
    def func():

            return i

    a = func
    lis.append(a)
print(lis)
Results: [<function func at 0x0000029E97472378>, <function func at 0x0000029E97472400>, <function func at 0x0000029E97472488>, <function func at 0x0000029E97472510>, <function func at 0x0000029E97472598>]

Lambda expressions can be nested
action = (lambdax: (lambda y: x + y))
a = action(10)
a(5)

Results: 15

This is a closure implemented with lambda. Like ordinary closures, embedded lambda expressions can obtain variables of upper lambda functions.
Use of anonymous functions
Anonymous functions are usually used as parameters of higher-order functions (functions with parameters). For example, several built-in functions: filter(), map(), reduce(). Let's take a look at the usage of these functions and the use of another feature of python to achieve the same effect.
filter function
lis = [1, 2, 3, 4]
re = filter(lambda x: x% 2 == 0, lis)
print(list(re))

result1 = [x for x in lis if x% 2 == 0]
print(result1)

Results: [2,4]
[2,4]

map function
lis = [1, 2, 3]
result = map(lambda x: x*2, lis) # Use lambda function
print(list(result))

result1 = [x*2 for x in lis] #use list comprehension
print(result1)

Results: [2, 4, 6]
[2, 4, 6]

reduce function
from functools import reduce

lis = [1, 2, 3, 4]
result = reduce(lambda x, y: x+y, lis)
print(result)

Results: 10

In the Python 2.x version, the recude can be imported directly. In the Python 3.x version, you need to import from the functools package
In addition to the special usage of the reduce function, the map and filter functions can be replaced by list comprehensions.
Related Article

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.