Python Lambda Functions

A lambda function can be defined as a function which can take a number of arguments, but returns output as a single expression only. In python, the lambda function is the one with no name. As we have discussed in the previous articles, we use the def keyword to define a simple function in python, similarly to define a lambda function, we can use the lambda keyword to define it. However, unlike normal functions, lambda functions will return only one value expression. We can also call lambda functions as anonymous functions in python. This is of most use when the user requires function objects.

Python Lambda Functions - Table of Content

So basically, the main use of lambda functions comes into play when a programmer requires a function without a name for a short duration of time. In this article, we will understand the properties of lambda function, their need in programming and lambda vs def() function in python.

Below is the syntax for writing the lambda function in python:

Python lambda arguments : expression

Below is a simple python program to understand how lambda functions are created:

z = lambda y:y+20

#Printing the function object

print(z)

print("The sum will be = ",z(20))

Output

 at 0x7f5879423dc0>

The sum will be = 40

>

In the above python code, the user has defined the lambda y: y+20 function, where y is an argument whereas y+10 is an expression. This code will work in such a way that the given expression will get evaluated and will return the output. Hence, we can say that this lambda function is similar to a normal python function.

Become a Python Certified professional by learning this HKR Python Training!Become a Python Certified professional by learning this HKR Python Training!Become a Python Certified professional by learning this HKR Python Training! Become a Python Certified professional by learning this HKR Python Training!

Properties of Lambda Functions:

  • Lambda functions can have n number of arguments, but they only return a single expression that is evaluated as an output. 
  • There is no limit to using lambda functions as the user can use them wherever he requires function objects.
  • The only limitation or restriction that a lambda function has is the return statement of a single expression.
  • Lambda expressions are not just used in as expressions in the functions, but also used by programmers in various fields.

Python Training Certification

  • Master Your Craft
  • Lifetime LMS & Faculty Access
  • 24/7 online expert support
  • Real-world & Project Based Learning

Here is another python code to elaborate the use of python strings with lambda functions:


string ='Welcome to HKR'

print(lambda string : string)

In the python code above, the user is not calling the print function however he is returning the stored function object as well as the memory location. Hence, if he wants to print the lambda function, he will have to perform the code in the way described below:


a ="Welcome to HKR"

(lambda a : print(a))(a)

Output

Welcome to HKR

>

Now, you see the lambda will get passed to the string and it will get printed.

Need for Python Lambda Function

When a user requires a nameless function, then he makes use of the lambda function in python. It is actually used as a function that takes in other functions in the form of arguments. Hence, lambda functions are made in use along with some built-in functions such as filter(), map(), etc. 

Let us now talk about some functions which are used along with lambda functions in python:

Lambda Function with filter()

Filter() is a built-in function in python that takes in a function and will list that as an argument. In this way, it will seep out all the elements from the sequence returning a whole new sequence which will evaluate True for the function.

Below is a python program to understand how a user can use filter() function is alongside lambda function:

list = (50,22,17,43,90,100,123,98)

oddlist = tuple(filter(lambda x:(x%2 == 0),list))

print(oddlist)

Output

(50, 22, 90, 100, 98)

>

Lambda Function with map()

In python, a map() function will take in both function and a list, unlike filter(). The user can call the function with all the contained items of the list which returns the function of each item.  

Below is a python program to understand how a user can use map() function is alongside lambda function:

my_list = [50,22,17,43,90,100,123,98]

list1 = list(map(lambda x: x * 2 , my_list))

print(list1)

Output

[100, 44, 34, 86, 180, 200, 246, 196]

>

Top 30 frequently asked Python Interview Questions!

Subscribe to our youtube channel to get new updates..!

Lambda Functions v/s def() Functions

Let us understand the difference between the lambda function and the normal python function using the python code below:

def cube(x):

    return x*x*x

lambda_cube = lambda x: x*x*x 

# using normal def() function

print(cube(3)) 

# using lambda function

print(lambda_cube(3))

Output

27

27

>

From the example mentioned above, we can clearly see that both python functions along with the lambda function work in a similar manner. But the difference lies here. Let us talk about it in a detailed fashion:

When the user uses the lambda function: the Lambda function will not have a return statement in python code. As we have discussed this fact earlier also, the lambda function will only return an expression. The lambda function can be put anywhere inside the code having no variable assigned to it. This is how the lambda function works in python.
When the user does not use the lambda function: Both the mentioned functions will return the cube of 3 (or any number that users will input). However, when the user inputs def(), he also needs to input the cube with a name and a value has to be assigned to it, unlike lambda function. Moreover, there has to be a return statement to get the output of the function.

Lambda Function with multiple statements in Python

Lambda functions in python do not permit multiple statements. But two lambda functions can be created using a trick. The user will be able to create two lambda functions in a code and call the second lambda function as one of the parameters of the first lambda function. Below is an example for better understanding:

List = [[50,22,17],[43,90,100],[123,98]]

sortList = lambda a: (sorted(i) for i in a)

secondLargest = lambda a, f : [b[len(b)-2] for b in f(a)]

res = secondLargest(List, sortList)

print(res)

OUTPUT

[22, 90, 98]

>

Here in this example, the lambda function is sorting the child-list of the main parent list. The list is passed as the other parameter which will then return n-2 items from the parent list which is sorted. Here, n is the actual length of the child-list. 

If you want to Explore more about Python? then read our updated article - Python Tutorial.

Python Training Certification

Weekday / Weekend Batches

Conclusion

This article can be concluded by understanding that lambda functions are those anonymous functions in python which are without a name. They basically are created to have an expression as a return statement-making our work easier and simpler. However, the user needs to be very careful about choosing between def() and lambda functions in a python code for accurate results.

Related Article:

1. Python Arrays

2. 8 Best Python IDEs

3. Python Functions

Find our upcoming Python Training Certification Online Classes

  • Batch starts on 1st Jun 2022, Weekday batch

  • Batch starts on 5th Jun 2022, Weekend batch

  • Batch starts on 9th Jun 2022, Weekday batch

Global Promotional Image
 

Categories

Request for more information

Kavya Gowda
Kavya Gowda
Research Analyst
Kavya works for HKR Trainings institute as a technical writer with diverse experience in many kinds of technology-related content development. She holds a graduate education in the Computer science and Engineering stream. She has cultivated strong technical skills from reading tech blogs and also doing a lot of research related to content. She manages to write great content in many fields like Programming & Frameworks, Enterprise Integration, Web Development, SAP, and Business Process Management (BPM). Connect her on LinkedIn and Twitter.