5 Python lambda Function with Examples

Spread the love

Python lambda is a anonymous function. Its created with lambda keyword. We can assign many arguments with one expression.

Syntax:

Lambda  Expression: arguments

Use of Lambda function:

It is used to create a function within the function for short period of time.

In this tutorial, you will learn about Python lambda Function with Examples

Example Program 1:  calculate power

power = lambda x: x ** 2 print(power(5))

 

Output: 25

Example Program 2: To print even numbers

my_list = [1,2,3,4,5,7,8,9,10] even = list(filter(lambda x: (x%2 == 0) , my_list)) odd = list(filter(lambda x: (x%2 != 0) , my_list)) print('Even Numbers',even) print('Odd Numbers',odd)

Output:

Even Numbers [2, 4, 8, 10]
Odd Numbers [1, 3, 5, 7, 9]

Example Program 3 : lambda program with map function

my_list = [1,2,3,4,5,7,8,9,10] even = list(map(lambda x: (x%2 == 0) , my_list)) odd = list(map(lambda x: (x%2 != 0) , my_list)) # Output: [4, 6, 8, 12] print('Even Numbers',even) print('Odd Numbers',odd)

 

Output:

Even Numbers [False, True, False, True, False, False, True, False, True]
Odd Numbers [True, False, True, False, True, True, False, True, False]

Example Program 4: Find biggest number

bigger_number = lambda x,y: x if (x>y) else y print(bigger_number(5,2))

Output:

5

Example Program 5: Find smallest number

small_number = lambda x,y: x if (x

Output:

2

admin

admin

Leave a Reply

Your email address will not be published. Required fields are marked *