What is lambda in Python?

What is lambda in Python?

Hello Buddies,

Today, We are going to learn about Lambda function in Python. We will see what is lambda in Python and how it works with examples. This tutorial goes into details on what is lambda in Python?

So, let's get started.

What is Lambda Function?

A Lambda function in python is an anonymous function or a function having no name. It is a short and restricted function having no more than singal line. Just like a normal function, a Lambda function can have multiple arguments with one expression. If you have a single expression to be executed, then the lambda function is extremely useful as compared to the traditional function defined using the def keyword.

 

Lambda Function Syntax

Here's the syntax of Lambda Function in Python Programming.

lambda argument(s) : expression

There can be a number of arguments but only one expression. The lambda function comes in very handy when workin gwith the map, filter, and reduce functions in Python. 

 

Comparison between lambda function & regular function

def multiple_by_2(x):
    return x*2

result = lambda x: x*2

print(multiple_by_2(5))
print(result(5))

output will be same

10

 

How to use Lambda Function in Python? Examples.

Example 1: Find a+b whole square using Lambda Function

squre = lambda a, b : a*2 + b**2 + 2*(a+b)
print(squre(2,5))

Output

43

 

Example 2: With map function to square eash list item

map_answer = map(lambda x : x*x, input_list)
print(list(map_answer))

Output

[4, 9, 16, 25, 36, 49]

 

Example 3: With filter function to filter list items with value greater than 4

filter_answer = filter(lambda x : x>4, input_list)
print(list(filter_answer))

Output

[5, 6, 7]

 

Example 4: With reduce function to sum all the list items

from functools import reduce
reduce_answer = reduce(lambda x,y:x+y,input_list)
print(reduce_answer)

Output

27

 

I hope it will help you.
Happy Coding :)

Leave a Comment

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

Go To Top
×