Python Lambda

Python is not inherently a functional language, but it adopted some functional concepts early on such as map(), filter(), reduce(), and the lambda operator was added to the language in January 1994.
In this tutorial, we are going to learn about these topics with some simple examples one by one. Let’s start with Python Lambda.


Python Lambda

In Python programming, lambda is like a small anonymous function. With the help of lambda keyword is used to create anonymous functions.
An anonymous function is a function without a name

Syntax

lambda arguments : expression

Any number of arguments can be takes in Lambda function, but the expression must be one.


Example of Python Lambda

add_one=lambda x: x + 1
print(add_one(1))

print((lambda x: x + 2)(1))
Output of the above program is

2
3

Description about Output

Here, x is an argument and x+1 is the expression. As we passed the 1 as the argument, so we have got 2 as the result. We can also apply the function above to an argument by surrounding both the function and its argument with parentheses ()

Example of Lambda using a simple function

def add_one(x):
 return x+1
print(add_one(1))
Output of the above program is

2


Function with more than one argument

Above, we passed the one argument as a lambda function argument. We can pass any number of argument as the argument, but the expression must be one.

Example of Lambda passing two arguments

# (lambda x,y: x + y)(2,3)
print((lambda x,y: x + y)(2,3))
Output of the above program is

5


Suggestions:

  • Try to write Python lambdas and use anonymous functions.
  • One should choose wisely between lambdas or normal Python functions.
  • Please avoid excessive use of lambdas.

Congratulations! Chapter Finished. Learn more about the similar topics:
Exercises & Assignments
No Content Found.
Interview Questions & Answers
No Content Found.