Python Lambda

Lambada is a small function usually written in one statement it can take any number of arguments but expression is only one Example.

x = lambda a : a + 10

In this code the a at the right side of lambda before the colon is an argument for function and after the colon there is a expression which one is calculated after the x function is called with value so this function will get an argument 5 and add it with 10 and the result of this function will be 15.

Lambda with 2 arguments

As there is mention above a lambda function can take as many arguments as you need to execute for example.

x = lambda a, b : a + b
print(x(10, 30))

In this function there are 2 arguments a and b and than add both of them and return the result. Similarly you can add as many arguments as you need for example if you need to evaluate 3 arguments than the expression would be like this.

x = lambda a, b, c : a * b *c
print(x(2, 3, 4))

This expression take 3 arguments and multiply them and return multiplication result. So you can add as many arguments at left side with comma separated and than evaluate them at right side.

Lambda in function

A lambda can be used in side the other function and than take argument first from main function than return a lambda function to a variable than it function can be called again For example.

def my_main_fun(n):
  return lambda a : a * n
x = my_main_fun(2)

In this function first we define main function and than call it when we call the main_function it took a argument 2 and replace with n at the right side of n and return a lambda function with expression lambda a : a * 2 Now


No we call the lambda function which is stored inside the x it will now multiply 3 by 2 and return answer as 6. So in this way we can use lambda function efficiently.

Leave a Comment

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s