In this Python article we want to learn about Python Lambda Function, so lambda function is a small and anonymous function that can be defined in single line and does not require a name. it can be used as stand alone function or as an argument to higher order functions like map(), filter() and reduce().
So first we need to define a list of words that will be used as function input. list will be generated randomly using the 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) |
Next 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] |
Finally 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
