Blog_Banner_Asset
    Homebreadcumb forward arrow iconBlogbreadcumb forward arrow iconData Sciencebreadcumb forward arrow iconPython lambda Functions with Practical Examples

Python lambda Functions with Practical Examples

Last updated:
21st Jun, 2021
Views
Read Time
9 Mins
share image icon
In this article
Chevron in toc
View All
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

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

upGrad’s Exclusive Data Science Webinar for you –

Transformation & Opportunities in Analytics & Insights

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.

Explore our Popular Data Science Courses

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

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.

Top Data Science Skills to Learn

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. 

Read our popular Data Science Articles

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.

Profile

Rohit Sharma

Blog Author
Rohit Sharma is the Program Director for the UpGrad-IIIT Bangalore, PG Diploma Data Analytics Program.

Frequently Asked Questions (FAQs)

1What is the difference between a normal function and a lambda function?

We know that a function in Python is defined using the def keyword. Similarly, a lambda function is defined using the lambda keyword. Consider the below example to deeply understand the difference between the two:
# Normal function def sq(x): return x*x # Lambda function lambda_sq = lambda x: x*x # Calling the normally # Defined function print(sq(10)) # using the lambda function print(lambda_sq(10)) }
The above example illustrates 2 functions calculating the square of a number. Without lambda, we have to create a function sq(x), and then return the square. On the other hand, with lambda, the whole function has boiled to a single line. Lambda does not require a return statement.

Explore Free Courses

Suggested Blogs

Top 13 Highest Paying Data Science Jobs in India [A Complete Report]
905094
In this article, you will learn about Top 13 Highest Paying Data Science Jobs in India. Take a glimpse below. Data Analyst Data Scientist Machine
Read More

by Rohit Sharma

12 Apr 2024

Most Common PySpark Interview Questions &#038; Answers [For Freshers &#038; Experienced]
20858
Attending a PySpark interview and wondering what are all the questions and discussions you will go through? Before attending a PySpark interview, it’s
Read More

by Rohit Sharma

05 Mar 2024

Data Science for Beginners: A Comprehensive Guide
5064
Data science is an important part of many industries today. Having worked as a data scientist for several years, I have witnessed the massive amounts
Read More

by Harish K

28 Feb 2024

6 Best Data Science Institutes in 2024 (Detailed Guide)
5150
Data science training is one of the most hyped skills in today’s world. Based on my experience as a data scientist, it’s evident that we are in
Read More

by Harish K

28 Feb 2024

Data Science Course Fees: The Roadmap to Your Analytics Career
5075
A data science course syllabus covers several basic and advanced concepts of statistics, data analytics, machine learning, and programming languages.
Read More

by Harish K

28 Feb 2024

Inheritance in Python | Python Inheritance [With Example]
17597
Python is one of the most popular programming languages. Despite a transition full of ups and downs from the Python 2 version to Python 3, the Object-
Read More

by Rohan Vats

27 Feb 2024

Data Mining Architecture: Components, Types &#038; Techniques
10774
Introduction Data mining is the process in which information that was previously unknown, which could be potentially very useful, is extracted from a
Read More

by Rohit Sharma

27 Feb 2024

6 Phases of Data Analytics Lifecycle Every Data Analyst Should Know About
80606
What is a Data Analytics Lifecycle? Data is crucial in today’s digital world. As it gets created, consumed, tested, processed, and reused, data goes
Read More

by Rohit Sharma

19 Feb 2024

Sorting in Data Structure: Categories &#038; Types [With Examples]
138996
The arrangement of data in a preferred order is called sorting in the data structure. By sorting data, it is easier to search through it quickly and e
Read More

by Rohit Sharma

19 Feb 2024

Schedule 1:1 free counsellingTalk to Career Expert
icon
footer sticky close icon