my_func = lambda x : x + 4 # x is an argument or parameter here print(my_func(10)) # -> 14
A lambda function is created using the lambda keyword. We do not use any def keyword or return keyword when creating a lambda function. Below is the basic syntax of a lambda function.
lambda arguments : expression
Lambda functions are defined without a name in python. Unlike functions in python, the lambda function can only have one expression. We wrote the expression in one line and execute it. A lambda function can have multiple arguments.
If there is a function that contains single expression and it does not need to define in a class somewhere else. Then you can make it lambda function. Also lambda function is highly used in python functions like map() and filters() where we check or apply function on list items.
We can create a lambda function with as many arguments as we want. Below is an example of a lambda function with multiple arguments.
addition = lambda a, b, c : a + b + c print(addition(2, 3, 6)) # -> 11
We have created a lambda function with 3 arguments a, b and c here. We are returning the sum of these arguments using this lambda function.
values = [20, 15, 30, 50, 40, 25] filtered_vals = filter(lambda val : val < 30, values) filtered_vals = list(filtered_vals) print(filtered_vals) # -> [20, 15, 25]
my_list = [3, 5, 6, 7] result = map(lambda x : x + x, my_list) result = list(result) print(result) # -> [6, 10, 12, 14]