⊗pyPmFnLa 16 of 128 menu

Lambda function in Python

Let's say we have a function func that takes a list and a callback as parameters. The function will create a new list from the elements of the original list. In this case, the callback will be applied to each of the elements:

def func(lst, callback): res = [] for el in lst: res.append(callback(el)) return res

Now let's create a function square that will square the number passed to it:

def square(num): return num ** 2

Let's pass a numeric list to the func parameters and a square function as a callback:

print( func([1, 2, 3], square) )

A new list consisting of squares of numbers will be output to the console:

[1, 4, 9]

However, this code can be significantly shortened by using a lambda function - an anonymous function that is called using the lambda keyword and written on a single line. Therefore, only functions whose code takes up one line can be rewritten as lambda functions.

The syntax of a lambda function looks like this:

lambda function parameter: operation on function parameter

Let's rewrite the square function using a lambda function and pass it to the func parameter:

print( func([1, 2, 3], lambda num: num ** 2) )

A lambda function can be written to a variable:

square = lambda num: num ** 2 print( func([1, 2, 3], square) )

Rewrite the following code using a lambda function:

def func(num, clb): return clb(num) def clb(num): return num + 1 print( func(2, clb) )

Rewrite the following code using a lambda function:

def func(num, clb1, clb2): return (clb1(num), clb2(num)) def clb1(num): return num + 1 def clb2(num): return num - 1 print( func(2, clb1, clb2) )

Rewrite the following code using a lambda function:

def func(num1, num2, clb): res = clb(num1) + num2 return res def clb(num): return num ** 3 print(func(2, 6, clb))
enru