Demystifying Lambda (Anonymous) Function in Python

In Python programming language, a lambda function is one-line function declared with no name and can have any number of arguments, but it can only have one expression.

These type of functions are capable of doing things similar to a regular function declared using the Python's def keyword.

Since lambda function is declared with no name so it is also known as Anonymous Function. Other names given to lambda function are Single Line Function, Single Use Function, Throw Away Function or Lambda Expression.

Lambda Function Syntax


function_name = lambda parameters : expression

Example & Comparison With Normal Function

In python, writing


square = lambda x: x*x

is equivalent to:


def square(x):
    return x*x

Examples

Example 1: Lambda Function To Find Square Of A Given Number (Lambda With One Argument)


square = lambda x: x*x

number = int(input('Enter any number: '))

result = square(number)

print('Square of %d is %d' %(number, result))

Output

Enter any number: 17
Square of 17 is 289

Example 2: Lambda Function To Add Two Numbers (Lambda With Two Arguments)


add = lambda x, y : x + y

number1 = int(input('Enter first number: '))
number2 = int(input('Enter second number: '))

result = add(number1, number2)

print('Sum of %d and %d is %d' %(number1, number2, result))

Output

Enter first number: 23
Enter second number: 11
Sum of 23 and 11 is 34

This article is not yet complete.