Python lambda Functions with Practical Examples
Updated on Dec 20, 2023 | 9 min read | 6.3k views
Share:
For working professionals
For fresh graduates
More
Updated on Dec 20, 2023 | 9 min read | 6.3k views
Share:
Table of Contents
Python lambda functions are those functions that are small and are defined without a name. In python, the keyword ‘def’ is used to define a function. However, in the case of anonymous functions, the keyword ‘lambda’ is used to define those functions. Therefore, the name “lambda functions. There might be a name or not assigned to the functions.
Compared to the regular functions in python, the lambda functions are short.
lambda functions have been added to the syntax of programming languages like Python, Java, C++, C#, etc. have in their syntax. While it is used as a core concept in Languages of ML or LISP.
The article will focus on the concept of python lambda functions and their use.
Based on the type of programming language, the lambda functions may be interchangeably used with the following terms:
Learn data science course from the World’s top Universities. Earn Executive PG Programs, Advanced Certificate Programs, or Masters Programs to fast-track your career.
Lambda calculation is a computation model based on which the lambda expressions are built upon. Lambda calculus is based on pure abstraction and was formalized by Alonzo Church. Also known as lambda abstractions, it refers to the original model created by Alonzo Church.
Any computation can be encoded by this concept.
The following syntax is used while using the lambda functions in python.
lambda arguments: expression
There can be any number of arguments in the lambda function in python. But the functions can have only one expression. This expression is first evaluated and then it is returned. The use of lambda functions lies wherever there is a requirement of the function objects.
Considering a case where an anonymous function with two arguments is defined with lambda but not bound to any variable:
lambda x, y: x + y
Here, the two arguments are taken by the function and the sum is returned.
There are a few characteristics shown by a lambda function:
upGrad’s Exclusive Data Science Webinar for you –
Transformation & Opportunities in Analytics & Insights
As mentioned there can’t be any statements while defining lambda functions. If the user uses statements like pass, return, raise, or assert, there will be a SyntaxError exception. The result of the exception can be shown through the below code
In contrast to all the standard normal functions in python, a lambda function in python can contain only a single expression. The body of the function lambda can have the expression spread all over through the use of multiple lines with parenthesis. However, it still remains as a single expression.
The string “odd” is returned when there is an “odd” argument while the string “even” is returned when there is an “even” argument. Two lines are used in the above code as they are within the parenthesis. But it remains as a single expression.
With the availability of “type hinting” in python, the normal functions are now being preferred over the lambda functions in python. With the availability of tools such as mypy, pyre, etc. type error can be caught with full_name(). The syntax error associated with the lambda function is raised during the run time.
The feature cannot be used outside a python interpreter. The definition of the lambda expression in python can be passed to functions of higher- order like map(), etc.
Different ways are supported in python lambda expressions for the passing of the arguments like:
The decorator can be defined as a pattern implementation allowing adding of a behavior to a class or a function. The syntax of @decorator is used as a prefix to a function for expressing a decorator in python
Only with the argument ‘Python’, the decorated_function() is printed. The additional behavior that gets printed is ‘Calling function ‘decorated_function’.
Python allows adding of a decorator to a lambda function, although the use of the syntax @decorator is not required. The decorator acts as a function which calls the lambda function.
<lambda> appears where the lambda function is identified. While, in the case of a normal function i.e. add_two, it is identified clearly.
For purposes of debugging, the lambda functions can be decorated in this way.
Closure
Closure() in python is defined as a function where free variables except parameters that are used in the function are bound to specific values that are defined within the scope of the function. We can call the closures from anywhere. Lambda functions in python can act as closures in a way the normal functions act as a closure.
Through the use of the modules doctest and unittest, the lambda functions in python can be tested:
In the code below, a function with the name “identity” is defined where an argument is returned. It is defined as a standard function of python through the use of the keyword “def”.
>>> def identity (x);
….. return x
Here, x is taken as an argument by the function “identity” and on being invoked it returns the argument.
Writing the same code using lambda will be:
lambda x: x
The expression consists of three parts: Lambda as the keyword, x which is then a bound variable, and X that is the body of the code.
The above expression can be elaborated as
>>> lambda x: x + 1
Here, the function is adding 1 to the argument. The function can be added to an argument while surrounding both the function along with the argument through the use of parentheses.
>>>(lambda x: x + 1)(2)
3
For computing the value in an expression, a reduction strategy is applied. Like, in the above example, the bound variable “x” can be replaced with argument 2.
(lambda x: x + 1 )(2) = Lambda 2: 2 + 1
= 2 + 1
= 3
The lambda function being an expression, naming can be done and the above code can be re written as
>>> add_one = Lambda x : x + 1
>>> add_one(2)
3
This is equivalent to writing:
def add_one(x):
return x + 1
A single argument is taken by the lambda functions. Also, while defining the lambda function in python there is no parenthesis around the functions.
For passing more than one argument to a python lambda function, the arguments are listed and separated through the use of a comma(,). There should be no parenthesis while listing the arguments. An example of multi-argument functions is shown below:
Here, two arguments are taken by the lambda function under full_name. A string is returned by the function that interpolates the first, and the last parameters. The code shows that while defining the lambda functions, there was no use of any parenthesis. Calling of the lambda function follows the same way as that of a standard function in python, i.e. using parenthesis that surrounds the arguments.
In python, the function filter(), accepts an argument as a list and a function. Through the items of the list, the function can be called which returns a new list of items. The function for this newly created list is evaluated to True.
An example of filter() function is shown below that is used for filtering even numbers contained in a list.
A list and a function is taken as an argument in the python map() function. All the items contained in the list call the function that returns a newly created list with items that are returned by the function.
Python lambda functions are those functions that are single-lined and are declared without a name, i.e. an anonymous function. Several numbers of arguments can be passed on to a lambda function which can have only one expression. Sometimes, the lambda function can be passed to other functions as an argument. The function when defined with the keyword ‘def’ in python can behave as a regular function.
The article, therefore, explained the concepts of lambda functions in python, their application with other functions and also a few examples. If you are further interested in gaining expertise over the programming language and mastering your coding skills, you can check the course “Executive PG Programme in Data Science” that is offered by upGrad. It is specially designed for all entry-level professionals within 21 to 45 years of age who want to achieve their skills of coding in data science. If you are willing to take a step towards your dreams, come forward and have a look at the benefits of the course. With hands-on industry projects, the course provided by IIIT-B, is designed to meet your needs and prepare you for the upcoming top industries.
Get Free Consultation
By submitting, I accept the T&C and
Privacy Policy
Start Your Career in Data Science Today
Top Resources