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.
1 2 3 4 5 6 |
import random words = ['apple', 'banana', 'cherry', 'date', 'elderberry', 'fig', 'grape', 'honeydew', 'imbe', 'jackfruit'] random.shuffle(words) print(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.
1 |
func = lambda x: [word for word in words if x in word] |
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.
1 2 3 4 5 6 7 8 |
import random words = ['apple', 'banana', 'cherry', 'date', 'elderberry', 'fig', 'grape', 'honeydew', 'imbe', 'jackfruit'] random.shuffle(words) func = lambda x: [word for word in words if x in word] print(func('a')) print(func('berry')) print(func('u')) |
This will be the result
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.
1 2 3 |
numbers = [1, 2, 3, 4, 5] squared_numbers = list(map(lambda x: x**2, numbers)) print(squared_numbers) |
Example 2: Using Lambda with filter()
Now, let’s use a lambda function with filter() to find even numbers in a list.
1 2 3 |
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] even_numbers = list(filter(lambda x: x % 2 == 0, numbers)) print(even_numbers) |
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.
1 2 3 4 5 |
from functools import reduce numbers = [1, 2, 3, 4, 5] product = reduce(lambda x, y: x * y, numbers) print(product) |
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