Lambda (Anonymous Function) in Python (with Examples)

Table of Contents

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.

lambda 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

Lambda Example & Comparison With Normal Function

In python, writing

square = lambda x: x*x

is equivalent to:

def square(x):
    return x*x

Lambda Function Examples

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

In this example, square is a lambda function which takes one argument x and it returns x*x.

square = lambda x: x*x

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

result = square(number)

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


Enter any number: 17
Square of 17 is 289

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

In this example, add is lambda function which takes two arguments x and y and it returns x+y.

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))


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

Example 3: Application of Lambda in Sorting

In python, function sorted() is used to sort any iterable. This function always retuns list.

Without applying lambda, let's look at the following code for sorting:

# Dictionary ordering of words

words = ['Ball', 'apple', 'cat', 'Ant','dog']

# Applying sorted function
result1 = sorted(words)
print('Result 1:', result1)


Result 1: ['Ant', 'Ball', 'apple', 'cat', 'dog']

But, Wait! This is not dictionary sorting as Ball comes before apple because, sorted() function returns result on the basis of ASCII sorting. But we can modify this using the concept of lambda as follows:

# Dictionary ordering of words
words = ['Ball', 'apple', 'cat', 'Ant','dog']

# Applying sorted function and lambda
result2 = sorted(words, key= lambda x: x.upper())
print('Result 1:', result2)


Result 2: ['Ant', 'apple', 'Ball', 'cat', 'dog']

In this example no name is assigned to lambda function, that is why we call it Anonymous Function.

Here lambda function takes each words in the list as argument and converts them to upper case while comparing.