If you are interested to learn about the Python frameworks
A lambda function is a small anonymous function. A lambda function is a single-line function declared with no name, which can have any number of arguments, but it can only have one expression. Such a function is capable of behaving similarly to a regular function declared using the Python’s def keyword. A lambda function can take any number of arguments, but can only have one expression. In Python, 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 <em>arguments </em>: <em>expression</em>
The expression is executed and the result is returned:
Add 10 to argument
a, and return the result:
x = lambda a : a + 10<br>print(x(5))
Lambda functions can take any number of arguments:
a with argument
b and return the result:
x = lambda a, b : a * b<br>print(x(5, 6))
c and return the result:
x = lambda a, b, c : a + b + c<br>print(x(5, 6, 2))
Is it good practice to use lambda in Python?
Lambdas are best suitable for places where small functions are needed and they are used just one time. One common usage of lambdas is to set it as the key argument in the built-in sorted() function.
What is the benefit of lambda in Python?
The lambda keyword in Python provides a shortcut for declaring small anonymous functions. Lambda functions behave just like regular functions declared with the def keyword. They can be used whenever function objects are required.
Why Use Lambda Functions?
The power of lambda is better shown when you use them as an anonymous function inside another function. Say you have a function definition that takes one argument, and that argument will be multiplied with an unknown number:
def myfunc(n):<br> return lambda a : a * n
Use that function definition to make a function that always doubles the number you send in:
def myfunc(n):<br> return lambda a : a * n mydoubler = myfunc(2) print(mydoubler(11))
Or, use the same function definition to make a function that always triples the number you send in:
def myfunc(n):<br> return lambda a : a * n mytripler = myfunc(3) print(mytripler(11))
Or, use the same function definition to make both functions, in the same program:
def myfunc(n):<br> return lambda a : a * n mydoubler = myfunc(2)<br>mytripler = myfunc(3) print(mydoubler(11))<br>print(mytripler(11))
Example of Lambda Function in python
Here is an example of lambda function that doubles the input value.
# Program to show the use of lambda functions double = lambda x: x * 2 print(double(5))
In the above program,
lambda x: x * 2 is the lambda function. Here x is the argument and
x * 2 is the expression that gets evaluated and returned. This function has no name. It returns a function object which is assigned to the identifier
double. We can now call it as a normal function. The statement
double = lambda x: x * 2
is nearly the same as:
def double(x): return x * 2
Use of Lambda Function in python
We use lambda functions when we require a nameless function for a short period of time. In Python, we generally use it as an argument to a higher-order function (a function that takes in other functions as arguments). Lambda functions are used along with built-in functions like
Example use with filter()
filter() function in Python takes in a function and a list as arguments. The function is called with all the items in the list and a new list is returned which contains items for which the function evaluates to
True. Here is an example use of
filter() function to filter out only even numbers from a list.
# Program to filter out only the even items from a list my_list = [1, 5, 4, 6, 8, 11, 3, 12] new_list = list(filter(lambda x: (x%2 == 0) , my_list)) print(new_list)
[4, 6, 8, 12]
Example use with map()
map() function in Python takes in a function and a list. The function is called with all the items in the list and a new list is returned which contains items returned by that function for each item. Here is an example use of
map() function to double all the items in a list.
# Program to double each item in a list using map() my_list = [1, 5, 4, 6, 8, 11, 3, 12] new_list = list(map(lambda x: x * 2 , my_list)) print(new_list)
[2, 10, 8, 12, 16, 22, 6, 24]
Using lambda() Function with reduce()
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.
Arguments In Lambda Functions
When it comes to arguments, there is no difference between lambda functions and a regular function. Lambda functions support all the ways of passing arguments supported by regular functions. Check out Python Functions to know more about Function’s arguments.
Lambda Function And Regular Functions
To recap, lambda functions are functions with no names and are sometimes called anonymous functions, lambda expressions. In this section, we will look at some similarities and differences between lambda functions and regular functions (functions defined with the def keyword).
Differences Between Lambda Functions and Regular Functions
Differences between Lambda Function and Regular Function.
|Lambda Function||Regular Function|
|It is created using the lambda keyword.||It is created using the def keyword.|
|Traceback identifies a lambda functions as .||Traceback identifies a regular function by its name.|
|Commonly written as a single-line code.||Can contain multiple-line code.|
|Can be invoked immediately(IIFE).||Can’t be invoked immediately.|
|Is not bound to a name.||It is bound to a name.|
|Do not support annotations.||Supports annotations.|
|Must have only one expression.||May have multiple expressions.|
|Doesn’t support statements.||Supports statements.|
|Must not contain a return statement, but returns its body automatically.||Must contain a return statement in order to return a value. Returns None if no return statement is present.|
The table above summarizes the differences between a lambda and a regular function. However, we shall elaborate more on those points in this section.
#1) Differences In Keywords
This is one of the basic and important differences. A lambda function is defined using the lambda keyword which is different from a regular function that uses the def keyword. The lambda keyword creates and returns an object while the def keyword creates and binds the object to the function’s name. Keyword differences between Lambda and Regular functions.
#2) Differences In Tracebacks
One of the reasons why lambda functions are not highly recommended is because of the way traceback identifies them. We shall see that, when an exception gets raised in a lambda function, the traceback will identify it as <lambda>. This can be hard to debug as it’ll be difficult to locate the specific lambda function in question. Traceback identifies regular functions differently and more appropriately by name. This makes them highly favored during debugging. Trigger the ZeroDivisionError exception and see how traceback differs in identifying them.
Traceback identification difference between Lambda and Regular functions.
|lambda traceback||def traceback|
|divide = lambda a,b: a/b|
# divide by zero to raise the ‘ZeroDivisionError’ exception
# divide by zero to raise the ‘ZeroDivisionError’ exception
#3) Difference In Line-Code
Lambda functions are commonly written as single-line code. However, they can also be expressed in multi-line code using the backslash(/) or parentheses(()).
As for regular functions, they are commonly expressed in a multi-line code but in cases where a single expression or statement is required, they can also be expressed in a single-line code as seen in example 3 above.
However, for clarity, it is recommended that a lambda function be expressed in a single-line code while regular functions are expressed in a multi-line code.
#4) Differences In Invocation
One of the advantages of lambda functions over regular functions is that they can be invoked immediately, also known as Immediately Invoked Function Execution( IIFE). This makes their definitions suitable as arguments to higher-order functions like map(), filter(), etc. Check example 2 above for a few examples.
If we try to apply this to a regular function, a SyntaxError will be raised.
#5) Difference In Binding
Since a lambda function is anonymous, it has no name, hence is not bound to a variable. Unlike a regular function that must be given a name during definition. This is one of the reasons why lambda functions are mostly used when reuse is not required.
#6) Differences In Annotation
Function annotations introduced in PEP 3107 enables us to attach metadata to our function’s parameters and return values. Unlike regular functions, lambda functions do not support annotations.
Annotations use colon(:) to attach metadata before any argument and an arrow(->) to set metadata for the return value. This doesn’t make it suitable for lambda functions as they don’t use parentheses to enclose their arguments and only support a single expression. Check the article on Documenting and Introspecting Python Functions to know more about function annotations.
#7) Differences In Expressions
Unlike regular functions, a lambda function only supports a single expression. Though the lambda function can be expressed in a multi-line code as seen in example 5, and it still remains a single statement.
#8) Differences In Statements
In Python, statements are actions or instructions that can be executed and are mostly made up of reserved keywords like return, raise, if, for. In Python, we can’t have statements inside expressions. This is why a lambda function can’t support statements as it is an expression in itself.
A lambda function doesn’t support a return statement, but automatically returns the result of its expression. A regular function on the other hand requires a return statement in order to return a value. A regular function without a return statement automatically returns None.
Similarities Between Lambda Functions And Regular Functions
Lambda function is just a function after all. Though they have some differences that we saw above, they also have some similarities. In this section, we shall take a look at some of their similarities.
#1) Execution By The Compiler
In a nutshell, a lambda function and a regular function with a single return statement have the same bytecode generated by the compiler during execution.
As we mentioned above, a lambda function is just a function. We can verify this claim with the built-in type() function as seen below. To verify the similarities in bytecode, we can use the dis module as seen below.
As we saw above, a lambda function is just a function. Hence, it supports the same ways of argument passing as regular functions. Check example 2 that demonstrates arguments in lambda functions.
A decorator is a feature in Python that allows us to add new functionality to an object without tempering with its original structure. This feature is very common in practice, so there is no doubt that a lambda function will support such a feature. Though it supports decorators, it doesn’t use the @ syntax for decoration, but simply calls the lambda function.
NB: Though the lambda function is assigned to a variable(bad practice), it is not bound to that variable. Hence, it is identified by <lambda>
A lambda function can be nested because it is just a function. However, it is rare due to its limitations (single expression, no statements, etc).
Whenever a simple single expression is needed, a lambda function can be used rather than binding a variable with the def statement. But still, we recommend using the def statement for readability and debugging purposes.
When To Use Lambda Functions
As stated above, a lambda function is a function without a name. That being said, the most important reason for using lambda functions is when we only need that function once and it only requires a single expression.
Mostly these lambda functions are used in Higher-order built-in functions like map(), filter(), reduce(), sorted(), min(), etc as arguments or key attribute’s value.
Note that this doesn’t mean that we can’t use lambda functions in higher-order functions, what we are trying to point out is that listcomps and generator expressions are preferred in many cases.
When Not To Use Lambda Functions
Lambda functions have their limitations and best practices. In this section, we will elaborate on a few.
#1) When Binding Is Required
In the PEP8 Guide, it is recommended to use a def statement instead of assigning a lambda function to a variable. Lambda functions are meant to be used directly and not saved for later usage.
#2) When Type Annotations Are Required
We may be tempted to apply annotations like in normal functions. However, lambda functions do not support type annotations. If it is required, then we are better off defining our functions with the def statement.
As we can see above, a SyntaxError is raised if we try to use type annotations in a lambda function.
#3) When Statements Are Required
We already saw above that lambda functions don’t support statements. It is very common too, for example, to raise exceptions in a function whenever we identify a problem. Unfortunately, a lambda function can’t incorporate a raise statement.