Python Lambda Function / Anonymous Function
Advertisement
In the previous blog, we learned about Python Inner Function and Closures. In this blog, you will learn about Anonymous Function in python i.e Python Lambda Function.
In Python, lambda functions are anonymous functions and are expressed in a single statement.
If you have a short function, that can be replaced by a lambda function with ease.
Python Lambda Function
Normally while defining a function in python we use the def
keyword but when an anonymous function is declared we use the lambda keyword. These functions have no name.
And thus called an anonymous function.
Python Lambda Function Syntax
lambda arguments: expression
The thing to keep in mind when using the lambda function is, there can be zero or multiple arguments separated by commas but only a single expression. Argument and expression in the lambda function are separated by a colon (:).
Expression in lambda functions is evaluated and returned. The whole lambda function returns a function object.
Learn Python list comprehension, an easy way to create a list in a single line.
The function object returned by the lambda function is stored in a variable. As the variable contains a function (Functions in python are also first-class citizens) it can be executed with the number of arguments passed in the lambda function.
Example of Lambda Functions in Python
square = lambda x: x**2
print(square(4))
Output: 16
In the above example, we have used the lambda function to return the square of a number. It takes one argument x in this case, the expression is x**2 which returns the square of the value x.
If the same example will be written using a normal function def
keyword.
def square(x): return x ** 2
print(square(4))
Use of Lambda Functions
Lambda Functions are mostly useful when you require a simple function but don’t want to give it any name.
It can also be used in Graphical user interfaces as a callback function and with functions like map()
and filter(
) in Python.
Hope you like it!
Learn about Python web Scraping to CSV, to know how to store the web scraped data in CSV form.