SoFunction
Updated on 2024-11-17

An in-depth analysis of Lambda function usage in Python

A lambda function is a small anonymous function.

lambda syntax

lambda function:

lambda [arg1 [,arg2,...[,argn]]] : expression

  • Input: any number of parameters can be accepted, such aslambda : print('hello')lambda x, y : x * y
  • Output: the value calculated by expression;
  • Function body: can only be a single line with an expression;
  • Functions are anonymous (no function name);

Example 1: A lambda function is similar to a normal function in that it can directly reference (in a readable way) an external variable.

gAll = 10
if __name__ == '__main__':
    count = 2
    result = map(lambda x: x * count + gAll, range(10))
    print(list(result))
# [10, 12, 14, 16, 18, 20, 22, 24, 26, 28]

Example 2: lambda function call (and the expression can be a simple if statement)

result = []
for i in range(10):
    ((lambda x: x * 2 if x % 2 == 0 else x)(i))
print(result)
# [0, 1, 4, 3, 8, 5, 12, 7, 16, 9]

Example 3: lambda delayed calculation caused by the problem (if you do not use the parameter, all prints are 9), in order to avoid this problem, you can pass i in as a parameter (similar to example 2), or directly assign i as a parameter a bit (similar to generating a local variable of the same name):

result = []
for i in range(10):
    # ((lambda: print("lambda:", i))) # all 9s
    ((lambda i=i: print("lambda:", i)))
for f in result:
    f()

(math.) higher order function

The lambda function can be used as the return value of a function to enhance its functionality; take power multiplication as an example:

def powMulti(n):
    return lambda x: x**n
if __name__ == '__main__':
    p = powMulti(2)
    for i in range(10):
        print(p(i))

Built-in higher-order functions

lambda can be easily applied to:

  • map(fun, iterable, ...): Shadowing; a generator that operates sequentially on elements of a collection with fun and returns the corresponding result;
  • reduce(fun, iterable[, initializer]): accumulate; operate on the set elements sequentially with fun (two arguments) (val = fun(val, ele); val initializes to initializer, or the first element in the set if ignored), returns the final result;
  • sorted(iterable[, cmp[, key[, reverse]]]): Sort;
  • filter(fun, iterable): Filtering;
src = [(0, 100) for _ in range(10)]
print(src)
dest = sorted(src)
print(dest)
ret = (lambda x, y: x + y, range(10), 10)
print(ret)  # 55

To this article on the in-depth analysis of the use of Python Lambda function is introduced to this article, more related Python Lambda content, please search for my previous articles or continue to browse the following related articles I hope you will support me in the future!