(Sponsors) Get started learning Python with DataCamp's free Intro to Python tutorial. Learn Data Science by completing interactive coding challenges and watching videos by expert instructors. Start Now!
Python allows you to create anonymous function i.e function having no names using a facility called lambda function.
lambda functions are small functions usually not more than a line. It can have any number of arguments just like a normal function. The body of lambda functions is very small and consists of only one expression. The result of the expression is the value when the lambda is applied to an argument. Also there is no need for any return statement in lambda function.
Let’s take an example:
Consider a function multiply()
def multiply(x, y):
return x * y
This function is too small, so let’s convert it into a lambda function.
To create a lambda function first write keyword lambda followed by one of more arguments separated by comma, followed by colon sign ( : ), followed by a single line expression.
r = lambda x, y: x * y
r(12, 3) # call the lambda function
Here we are using two arguments x and y , expression after colon is the body of the lambda function. As you can see lambda function has no name and is called through the variable it is assigned to.
You don’t need to assign lambda function to a variable.
(lambda x, y: x * y)(3,4)
Note that lambda function can’t contain more than one expression.
Other Tutorials (Sponsors)
This site generously supported by DataCamp. DataCamp offers online interactive Python Tutorials for Data Science. Join over a million other learners and get started learning Python for data science today!