Creating anonymous functions with lambda

Anonymous functions are created using the lambda statement in Python. Functions that are not bound to a name are called anonymous functions.

Getting ready

If you followed the section on passing functions as a parameter, the example in this section is very similar to it. We passed a predefined function in that section; here we will pass a lambda function.

How to do it…

We will see a simple example with a toy dataset to explain anonymous functions in Python:

# 1.	Create a simple list and a function similar to the
# one in functions as parameter section.
a =[10,20,30]

def do_list(a_list,func):
    total = 0
    for element in a_list:
        total+=func(element)
    return total

print do_list(a,lambda x:x**2)   
print do_list(a,lambda x:x**3)   


b =[lambda x: x%3 ==0  for x in a  ]

How it works…

In step 1, we have a function called do_list that accepts another function as an argument. With a list and function, do_list applies the input function over the elements of the given list, sums up the transformed values, and returns the results.

Next, we will invoke the do-list function, the first parameter is our input list a, and the second parameter is our lambda function. Let's decode our lambda function:

lambda x:x**2

An anonymous function is declared using the keyword, lambda; it's followed by defining a parameter for the function. In this case, x is the name of the parameter passed to this anonymous function. The expression succeeding the colon operator is the return value. The input parameter is evaluated using the expression and returned as the output. In this input, the square of the input is returned as the output. In the next print statement, we have a lambda function, which returns the cube of the given input.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset