python

Lambda functions in python

Lambda Functions is one of the most powerful concepts in Python. Lambda functions are referred to as anonymous functions in python.

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.

Why do we use lambda functions?

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.

Create lambda function with multiple arguments

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]
The above code example shows the use of the lambda function inside a filter() function. Here we are filtering the given list values items. The filter() method returns the list items that have a value of less than 30
my_list = [3, 5, 6, 7]

result = map(lambda x : x + x, my_list)

result = list(result)

print(result)

# -> [6, 10, 12, 14]
We are using the lambda function in map() function in the above code snippet. the map function is returning the double of each element of the list items.
Was this helpful?