Lambda Function in Python

In this tutorial we want to learn about Lambda Function in Python, so lambda function is a small and anonymous function that can be defined in single line and does not require a name. you can use that as stand alone function or as an argument to higher order functions like map(), filter() and reduce(). 

 

 

Generating Random List of Words

So first we need to define a list of words that will be used as function input. list will be generated randomly using random module in Python. this is the code for generating a random list of words.

 

 

 

Defining Lambda Function

After that we are going to define lambda function. this function will take a string as input and return a list of words from the random list that contain input string as a substring. this is the code for the lambda function.

 

 

Testing the Function

And at the end we need to test the function with few inputs to make sure it works correctly. this the complete code.

 

 

 

This will be the result

Lambda Function in Python
Lambda Function in Python

 

 

 

 

Now let’s create some more examples on Python Lambda Function

 

 

Example 1: Using Lambda with map()

Let’s use a lambda function with map() to square each number in a list.

 

 

 

Example 2: Using Lambda with filter()
Now, let’s use a lambda function with filter() to find even numbers in a list.

 

 

 

Example 3: Using Lambda with reduce()
Lastly let’s use a lambda function with reduce() to find the product of all numbers in a list. Note that reduce() is in the functools module.

 

 

 

So we can say that Lambda functions in Python are powerful function for writing anonymous functions. They are particularly useful when used as arguments to higher order functions like map(), filter(), and reduce(). 

Subscribe and Get Free Video Courses & Articles in your Email

 

Leave a Comment

Share via
Copy link
Powered by Social Snap
×