Lambda Functions in Python

Beginners Code Computer Skills Python Web Development

Lambda Functions

In simple words, Lambda functions can be defined as a form of non-standard function. By non-standard we mean that these functions are not defined in a regular form of the definition of functions.

Since these functions are defined in an irregular manner, sometimes they are also called as anonymous functions. This term can be attributed to either its irregular format or expression return style.

Lambda can accept any number of arguments we provide to it, but it will return only one value which will in the form of a string expression.

The syntax of the Lambda Function is as follows:

mario = lambda coin, mush: coin + mush
print("The next castle number is", mario(4,5))

Here the variable mario  stores the parameter provided manually. When it is called, it takes the values to the lambda function and executes the required expression.

It means we have to use the lambda keyword followed by arguments of the function. Followed by a colon, we provide the expression to deal with the arguments.

Uses of Lambda Function

Lambda can be better used when they are used to pass arguments to a higher function. In these cases, we don’t have only one variable to pass, rather there can be a large amount of input to deal with it. In such cases, instead of passing the single values, we create a lambda function, and the function passes the value iteratively.

The following example will make it clear:

def add(num):
    return lambda sum: sum + num

def main():
    num = int(input("Enter the number"))
    store = add(num)
    for i in range(1, 51):
        print(num, "+", i, "=", store(i))

main()

The following code prints the sum table of the provided number num  till 50. We create a lambda function inside a regular function add() which does the summation of the num till 50. When the store is declared and assigned with the regular add() function, then it takes up the value of sum from the add() function as a parameter.

This important concept enables us to use lambda Iteratively.

Later in the looping part, the sum value is passed as a parameter from the store  variable and thus we generate a summed table.

Note: For better insight, I would suggest all run the code and verify the steps. Make the necessary changes, and you can understand how this works.