Python Supports the Creation of Anonymous functions at Runtime

Yes, Python supports runtime anonymous functions. A function without any name is known as an anonymous function.

Lambda function Syntax

lambda parameters: expression

Let’s understand with following single line example for adding two number

def add(x, y):
    return x + y
print("Summation Value:",add(5, 2))

Output: ('Summation Value:', 7)

Here function add has one expression to execute therefore we can replace such single expression by defining anonymous function Lambda.

Normal function in python is declared using def keyword whereas anonymous function is declared using lambda keyword.

Let’s rewrite above example code using Lambda as below

sum_number = lambda a, b: a + b
print("Summation Value:",sum_number(5, 2))
    

Output: : ('Summation Value:', 7)

This lambda function is invoked run time and returns results based on input provided. Let's go through more relevant commonly asked Quizzes and Definitions.

1. Filter Odd number from the list of mixed even and odd numbers

numbers = [13, 90, 17, 59, 21, 60, 5] 
odd_list = list(filter(lambda x: (x%2 != 0) , numbers))
print(odd_list)
    

Output:

[13, 17, 59, 21, 5]
    

Explanation:
Here lambda expression lambda x: (x%2 != 0) executed at runtime and return results with odd numbers. Lambda is used here with an inbuilt function filter to select only odd numbers from the given list.

Lambda construct can have multiple input arguments with one expression.

2. Does Lambda support the inclusion of a return statement?

No. Anonymous only includes expression. It does not include return, assert or pass. It will raise SyntaxError: invalid syntax if used with such statements.

Let’s explore with the following program:

sum_number = lambda a, b: return a + b
print("Summation Value:",sum_number(5, 2))
   

Output: SyntaxError: invalid syntax

Explanation: In above example used return statement inside lambda function which cause error as invalid syntax. Lambda function already return return result of expression a + b. We don't need to use return statement here. Let's remove return and re write above code in following way

sum_number = lambda a, b:  a + b
print("Summation Value:",sum_number(5, 2))
   

Output: ('Summation Value:', 7)