Everything You Need to Know About Lambda in Python

Lambda in Python is a keyword to define anonymous functions. As you might know, it is common to use the def keyword to define a normal function. Similarly, the lambda keyword is used when you have to define an anonymous function. Thus, an anonymous function is also known as a lambda function in Python. You can call these Python lambda functions as soon as you define them.

Syntax of Lambda in Python

lambda arguments: expression

You can use as many arguments as you want in a lambda function, but it can have only one expression. This expression is evaluated and returned as a result. Let’s have a look at an example to understand the concept of lambda function in Python better.

Example: Using Lambda Function in Python

def squ(x):

return x*x

lambda_squ = lambda x: x*x

# Printing both the outputs

print(squ(7))

print(lambda_squ(7))

Output:

LambdainPython_1.

As you can see in the output, both the functions squ() and lambda_squ worked as intended, and gave the same result. However, while defining the normal function squ(), you had to describe the function and pass the return statement to get the output. On the other hand, while using the lambda function lambda_squ(), you didn’t have to give the return statement. Thus lambda in Python provides a more straightforward way to write shorter and temporary functions.

FREE Data Science With Python Course

Start Learning Data Science with Python for FREEStart Learning
FREE Data Science With Python Course

Why Is the Python Lambda Function Used?

Lambda function in Python is used for numerous reasons. The primary uses of Python lambda are:

  • When you want to define temporary nameless functions
  • To pass it as an argument to other higher-order function that takes functions as an argument
  • To create a function that is callable as soon as defined

Which Functions in the Python Standard Library Leverage Lambdas?

Because of the many benefits and uses of Python lambda functions, you can use them with several built-in functions such as:

Let’s look at how to use Lambda in Python with these built-in functions.

Example: Using Python Lambda Functions With filter()

As the name gives out, the filter() function is used to filter a sequence’s elements. You can pass any sequence such as lists, sets, tuples, and so on. It takes into account two parameters:

  • Function: The function that needs to be applied
  • Sequence: The sequence on which the function needs to be applied

The Python filter() function applies the mentioned function to each element of the sequence and returns the filtered result consisting of the elements that returned true after the function execution.

In the below code, you will use two filters () functions. The first one to get only the numbers divisible by three, and the second to get only numbers greater than 50 from a list.

# Defining the list

example_lst = (5, 21, 72, 102, 16, 123, 65, 85, 19, 90)  

# Passing the lambda function

divisible_lst = list(filter(lambda i:(i%3 == 0),example_lst))

print(divisible_lst)

# Passing the second lambda function

greater_lst = list(filter(lambda i:(i>50), example_lst))

print(greater_lst)

Output:

LambdainPython_2

Example: Using Lambda Function in Python With map()

The Python map() function is used to pass a function through each item in an iterable. Like the filter() function, even map() accepts the same two parameters: function and sequence. It iterates through the sequence and applies the specified function to each element.

For this example, you will use the same list as the last example, and two map() functions. The first one will apply a function to add a number to itself, and the second one to multiply a number by itself. Let’s check what you get as an output.

# Defining the list

example_lst = (5, 21, 72, 102, 16, 123, 65, 85, 19, 90)  

# Passing the lambda function

duble_lst = (list(map(lambda i:i*2, example_lst)))

print(duble_lst)

# Passing the second lambda function

square_lst = (list(map(lambda i:i*i, example_lst)))

print(square_lst)

Output:

LambdainPython_3

Example: Using Lambda in Python With reduce()

The reduce() function in Python is used to apply a function to each element of the specified sequence. Python 3, reduce() became a part of the functools module. Hence, you have to import the functools module to work with the reduce() function. It again accepts two parameters: function and sequence.

It will first apply the function to the first two elements of the sequence. Next, it will take the result of the first execution as the first argument and the next element of the sequence as the second argument and apply the function to them. The reduce() function continues doing this until no element is left in the sequence. Let’s look at an example to understand it better. Take the same list in the code below and two reduce() functions. The first reduce() will do addition, and the second will find out the greatest number.

from functools import reduce

# Defining the list

example_lst = (5, 21, 72, 102, 16, 123, 65, 85, 19, 90)  

# Passing the lambda function

sum_lst = reduce((lambda i,j: i+j), example_lst)

print(sum_lst)

# Passing the second lambda function

max_value = reduce((lambda i,j: i if i>j else j), example_lst)

print("The Greatest Number of the List is: ", end="")

print(max_value)

Output:

LambdainPython_4

When to Use Lambda in Python?

At the interpreter level, even the lambda functions are treated as regular functions. Hence, it is essential to understand which ones to use when. The best time to use lambda functions in Python is:

  • When you want to define a short function for temporary use
  • While defining a function that returns a single expression
  • When you want to create a one-time use function to pass as an argument to another function (example: sort(), sorted(), min(), max())

When to Avoid Lambda Functions in Python?

At the core, the best use of lambda in Python is to define shorter one-time use functions. Hence, if the code is becoming too complex, it is best to avoid it.

Even though you can write a complex code in one sentence with lambda functions, it is recommended to define a regular function in such cases to make your code more straightforward and easy to understand.

It is also recommended to avoid lambda functions in Python if:

  • You think you are abusing it (more about it later in this article)
  • It does not follow the PEP 8 style guide
  • It becomes cumbersome and unreadable
  • For raising an exception

How to Test Lambda in Python?

Testing your code in Python is essential to ensure that it runs as it was meant to be. The lambda functions in Python can be tested in the same way as regular ones using unittest and doctest.

Example: Testing Lambda Functions in Python Using unittest

You can use the Python unittest module to test a lambda function like a regular one. In the code below, you will be testing a simple lambda function to multiply a number by two using the unittest module.

import unittest

mul_two = lambda x: x*2

class Test_Example(unittest.TestCase):

    def test_mul_three(self):

        self.assertEqual(mul_two(3), 6)

    def test_mul_four_point_five(self):

        self.assertEqual(mul_two(4.5), 9.0)

    def test_mul_seven(self):

        # Should fail

        self.assertEqual(mul_two(7), 13)

if __name__ == '__main__':

    unittest.main(verbosity=2)

Output:

LambdainPython_5

LambdainPython_5.1

LambdainPython_5.2

LambdainPython_5.3

As you can see in the code above and its result, you have defined a Test_Example class with three test functions for different scenarios for the mul_two lambda function. As expected, you received two OK and one FAIL result. The OK results were for test_mul_three and test_mul_four_point_five functions as the answers were 6 and 9.0, respectively. On the other hand, the FAIL output was for the test_mul_seven function as the answer for 7*2 is 14 and not 13.

Example: Testing Lambda Functions in Python Using doctest

You can also use the doctest module to test lambda functions. However, the doctest module uses docstring, which lambda rarely supports for testing. But you can assign a string to the __doc__ element to test lambda functions. Let’s consider the same example of multiplying a number by two and testing it with doctest.

mul_two = lambda x: x*2

mul_two.__doc__ = """Multiply a number by two.

    >>> mul_two(3)

    6

    >>> mul_two(4.5)

    9.0

    >>> mul_two(7) # Will fail

    13

    """

if __name__ == '__main__':

    import doctest

    doctest.testmod(verbose=True)

Output:

LambdainPython_6

LambdainPython_6.1

LambdainPython_6.2

In the above code, you used the same test case as for the unittest and got the same result with two passed and one failed test.

What Do Lambda Expression Abuses Mean?

Lambda expression abuses mean trying to overcome something that is not supported by lambda. A simple example would be the use of the doctest module you did in the previous example. A typical lambda function does not support docstring. But you still passed it using the __doc__ element and tried to overcome it.

Other abuse examples would be:

  • Trying to overcome the fact that lambda functions do not support statements
  • Fixing several lines of code in a single line of lambda and making it difficult to read
  • Raising an exception

Python Training Course

Learn Data Operations in PythonExplore Course
Python Training Course

What Are the Alternatives to Lambda in Python?

Lambda functions in Python have several benefits. But at times, you might need to avoid its use. For this very reason, it is essential to know about the alternatives to lambda functions, which are list comprehensions and generator expressions. You can use these alternatives with the map, filter, and reduce functions.

Example: Using Alternatives to Lambda Functions in Python for map()

The below example uses the map() function with both lambda and its alternative: list comprehension. Here, you will capitalize the first letter of all the words

print(list(map(lambda i: i.capitalize(), ['ferrari', 'lamborghini', 'jeep'])))

print([i.capitalize() for i in ['ferrari', 'lamborghini', 'jeep']])

Output:

LambdainPython_7

As you can see in the above output, both the codes gave the same outcome. However, while using the lambda function, you had to convert the object to a list to make it readable. On the other hand, while using the list comprehension, you were directly able to print it with no conversion required.

Example: Using Alternatives to Lambda in Python for the Filter()

The example below uses the filter() function with both lambda and list comprehension and the range() function to create a list with odd numbers.

print(list(filter(lambda i: i%2 != 0, range(15))))

print([i for i in range(15) if i%2 != 0])

Output:

LambdainPython_8

In the code above, you had to convert the lambda function object to a list, but the list comprehension provided an efficient way of printing the same result.

Example: Using Alternatives to Lambda Functions in Python for reduce()

For this example, you will be using three different ways to add only the numbers from a pair of an alphanumeric list. The first method is using the lambda function, the second is using generator expression, and the third is a simpler way of using generator expression.

import functools

example_pairs = [(3, 'x'), (5, 'y'), (7, 'z')]

print(functools.reduce(lambda acc, pair: acc + pair[0], example_pairs, 0))

example_pairs = [(3, 'x'), (5, 'y'), (7, 'z')]

print(sum(i[0] for i in example_pairs))

example_pairs = [(3, 'x'), (5, 'y'), (7, 'z')]

print(sum(i for i, _ in example_pairs))

Output:

LambdainPython_9.

As you can see, the output for all the ways was the same, but generator expression provided much more efficiency.

Looking forward to making a move to the programming field? Take up the Python Training Course and begin your career as a professional Python programmer

Summing It Up

In this article, you learned everything about the anonymous lambda functions in Python. You have also seen where to use and where to avoid them, along with available alternatives. Knowing when and where to use lambda in Python efficiently will help you define and use short-term functions for more straightforward and quicker code. 

Like lambda and list comprehension, various other Python programming concepts can help you save an ample amount of time while coding. You can refer to Simplilearn’s Python Tutorial for Beginners to get acquainted with all such concepts. Further, if you want to go advanced, you can opt for our Online Python Certification Course to excel in Python development. You can also take our Data Science with Python Certification Course if you are more in data analytics.

Do you have any questions for us? Leave them in the comments section of this article. Our experts will get back to you on the same, at the earliest!

About the Author

SimplilearnSimplilearn

Simplilearn is one of the world’s leading providers of online training for Digital Marketing, Cloud Computing, Project Management, Data Science, IT, Software Development, and many other emerging technologies.

View More
  • Disclaimer
  • PMP, PMI, PMBOK, CAPM, PgMP, PfMP, ACP, PBA, RMP, SP, and OPM3 are registered marks of the Project Management Institute, Inc.