An anonymous function is a function that is defined without a name. While normal functions are defined using the def keyword in Python, anonymous functions are defined using the lambda keyword.
These functions replace traditional user-defined functions having two or more lines with a simple one-line function. Creating the Lambda function is faster than creating it using the traditional way. It can have multiple arguments with one expression.
The syntax for lambda functions in python.
lambda argument (s) : expression
Example 1 :
Lambda functions can be used along with built-in functions like filter(),map() and reduce().
The filter function is used to select some particular elements from a sequence of elements by filtering them using an expression. The sequence can be any iterator like lists, tuple and sets etc.
The Map function is used to apply a particular operation to every element in a sequence. Like filter(), it also takes 2 parameters. One is a user-defined function and another is an iterator.
The reduce() function in Python takes in a function and a list as an argument. The function is called with a lambda function and an iterable and a new reduced result is returned. This performs a repetitive operation over the pairs of the iterable. The reduce() function belongs to the functools module.
Lambda functions are used when you need a function for a short period of time. This is commonly used when you want to pass a function as an argument to higher-order functions, that is, functions that take other functions as their arguments.ssss