Programs

Python lambda Functions with Practical Examples

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:

  • Anonymous functions
  • Lambda functions
  • Lambda expressions
  • Lambda abstractions
  • Lambda form
  • Function literals

Lambda Calculus

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.

Syntax of lambda function:

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:

  • There can’t be any statements in the body of the lambda function but can contain only expressions.
  • The execution code is just a single line.
  • Type annotations are not supported by the lambda function in python.
  • Immediate invocation is allowed.

Statements cannot be used

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 

Source

In the above code, a syntax error resulted when the code was parsed that contained the assert statement in the body of the function lambda.

lambda function contains only a single expression

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.

Source

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.

Type annotations

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.

Immediately Invoked Function Execution (IIFE)

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.

Arguments in a lambda function

Different ways are supported in python lambda expressions for the passing of the arguments like:

  • Positional arguments
  • Named arguments also known as keyword arguments
  • Variable list of arguments which is also referred to as varargs.
  • Variable list of keyword arguments
  • Arguments with only keywords.

Decorators in a Python Lambda Expression

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

In the below code, the function some_decorator(), adds the behavior to the decorated_function(). On the invoking of the function decorated_function(), the output shown below is generated.

Output:

Source

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. 

In the above code, on line 11, @trace decorates add_two() and is invoked by line 15 argument 3. Immediate involvement of a lambda function is observed in line 18. The following output is generated using the code:

Source

<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.

Use of lambda functions

  • Whenever we require using a function for a shorter time, the lambda functions are used in that case. 
  • For the passing of functions to a function of a higher-order function, lambda functions are applied. The functions are passed as arguments to those higher-order functions.
  • The lambda functions in python can be used with other built-in functions like map(), etc.

Testing lambda functions

Through the use of the modules doctest and unittest, the lambda functions in python can be tested:

  • Unittest modules test the lambda functions like the regular functions.
  • In the case of the doctest module, the python code is extracted from docstring, for the execution of the test. The syntax of the lambda function doesn’t allow the docstring. But, a string can be assigned to the _doc_ element of the lambda that is being named.

Examples of Python Lambda Functions

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.

  • Bound variable refers to the argument that is passed to a lambda function. However, free variables are those which are not bound and can be referenced in the expression body.  A constant can be a free variable or variables that are defined in the function’s scope.

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.

Python lambda functions with filter()

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.

Source

The output generated by the program is the new list: [4, 6, 8, 12].

Python lambda function with map()

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. 

An example of code using the map() function with the python lambda function 

Source

The output is the list containing the elements [2, 10, 8, 12, 16, 22, 6, 24].

Conclusion

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.

Prepare for a Career of the Future

0 replies on “Python lambda Functions with Practical Examples”

Accelerate Your Career with upGrad

Our Popular Data Science Course

×