The Python lambda function is anonymous means, a function without a definition keyword and name. To create this function, we have to use the Python lambda keyword and the syntax of the expression is
lambda arguments: expression
This lambda function accepts any number of arguments. However, it takes only one expression. For instance, Python lambda a, b: a + b. Here, a and b are the arguments accepted by the function, a + b is the expression.
Python lambda Function Examples
The following list of examples helps to learn the Python lambda functions.
Use the following statement to display the True or False as an output. It can make you understand that you do not need any argument to create a Python lambda expression.
num = lambda: True print(num())
With no arguments output
Python lambda Sum
We are using the Python lambda expression to add 5 to the given argument value. It accepts one value because we specified one argument after the keyword. After the colon, it is an expression or the functionality it has to perform when we call this anonymous function.
num = lambda a: a + 5 print(num(10))
We passed 10 as the argument. 10 + 5 = 15.
In this Python lambda Sum example, we are using two arguments to perform addition or find the sum of two numbers. It means we have to assign two values while calling this expression.
add = lambda a, b : a + b print(add(10, 20))
Generally, we can achieve the same by declaring or creating a method. This time, we are using the Python lambda expression and normal function. Both give the same result.
add = lambda x, y : x + y
print("\nResult from a Function")
def add_func(x, y):
return x + y
Both this and normal functions are returning the same result. However, the normal Python function needs a def keyword for function definition, method name, and a return value. Whereas, this method does not need any of them. By default, it returns the expression result.
30 Result from a Function 30
These expressions are not about adding two values. We can perform multiplication, subtractions, or any other calculations in Python lambda expression. Here, we are multiplying two argument values.
multi = lambda a, b : a * b print(multi(5, 20)) print("\nResult from a multi") def multi_func(a, b): return a * b print(multi_func(5, 20))
100 Result from a multi 100
In this Python lambda Function example, we are using three arguments. Next, we are multiplying those three argument values.
multi =lambda a, b, c : a * b * c print(multi(5, 2, 6)) print("\nResult from a multi") def multi_func(a, b, c): return a * b * c print(multi_func(5, 2, 6))
With three arguments output
60 Result from a multi 60
Until now, we used this Python lambda Function expression to calculate something and return results. However, use the print statement to print the output as well. The below code prints Hello World! as an output.
We can also achieve the same result by calling that statement with parenthesis from the shell itself.
Default Argument Values of lambda expression
In this Python lambda expression example, we assigned default values to all three arguments. Next, we are adding, and multiply three of them. If we have the default values, we do not have to pass values while calling them.
add = lambda x = 10, y = 20, z = 30 : x + y + z print(add()) # 10 + 20 + 30 multi = lambda x = 10, y = 20, z = 30 : x * y * z print(multi()) # 10 * 20 * 30
However, you can override the default values by passing new values as the arguments. Here, the first print statement overrides 10 with 12, 20 with 14 and 30 with 16. It means, x = 12, y = 14 and z = 16. In the second statement, x = 75, y = 126 and z = 30.
add = lambda x = 10, y = 20, z = 30 : x + y + z
print(add(12, 14, 16)) # 12 + 14 + 16
print(add(75, 126)) # 75 + 126 + 30
print(add(222)) # 222 + 20 + 30
print(add()) # 10 + 20 + 30
multi = lambda x = 10, y = 20, z = 30 : x * y * z
print(multi(2, 4, 5)) # x = 2, y = 4, z = 5
print(multi(100, 22)) # x = 100, y = 22, z = 30
print(multi(9)) # x = 9, y = 20, z = 30
print(multi()) # 10 * 20 * 30
Python lambda function without Arguments
If you don’t want to pass any arguments, however, you want to return something from it, then you can use this kind of statement.
We do not have to pass any argument values to call these expressions. Whenever we call them, they return the same result.
add = lambda : 10 + 20 print(add())
If we replace + with * (10 * 20) in the above example, we can get the multiplication result. And the output of 10 * 20 = 200.
Python Anonymous Functions using lambda
It is powerful when we use this anonymous function inside a method. Here, we declared a function that accepts one argument. Inside the method, we used this expression to multiply that value with the unknown number of times.
def new_func(n): return lambda a : a * n number = new_func(2) print(number(50))
It calls new_func method where n = 2. It means, the method returns a: a * 2. Then, we assigned that value to the number (lobject)
number = new_func(2)
Next, we called that number with 50 (this is the argument value. It means, 50 : 50 * 2 => 100
Calling this method with different values. First with 2, and then with 3.
def new_func(n): return lambda a : a * n number1 = new_func(2) number2 = new_func(3) print(number1(50)) print(number2(50))
Python Lambda Built-in Functions
We can use the available Built-in methods along with this function.
lambda function with filter Example
We use the built-in filter function to filter the sequence of list items. First, we declared a list of numbers from 1 to 15. Next, we used the filter method with this expression. This Python lambda filter expression checks whether a number is divisible by two or not. Next, the filter method returns all the True values.
This filters method and returns the Even Number, and Odd Numbers. Refer to the List article
number = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15] print(number) even_num = list(filter(lambda x : x % 2 == 0, number)) print(even_num) odd_num = list(filter(lambda x : x % 2 != 0, number)) print(odd_num)
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15] [2, 4, 6, 8, 10, 12, 14] [1, 3, 5, 7, 9, 11, 13, 15]
map lambda expressions Example
Unlike filter, map function takes each list item and returns both the True and False values. In this Python lambda map example, we used map method to return the boolean value. It checks each individual value is divisible by 2 equals to 0. If true, it returns True. Otherwise, it returns false.
number = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] print(number) new_num = list(map(lambda x : x % 2 == 0, number)) print(new_num)
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
[False, True, False, True, False, True, False, True, False, True]
This time, we are performing multiplication using the map function. It takes one individual list item at a time and performs the multiplication. At last, the expression returns the modified list.
number = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] print(number) double_num = list(map(lambda x : x * 2, number)) print(double_num)
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10] [2, 4, 6, 8, 10, 12, 14, 16, 18, 20]
If you replace the above expression x : x * 2 with x ** 2, the output will be [1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
By using the map function, you can also perform calculations on multiple lists. For instance, this example performs addition, subtraction, and multiplication of two lists. It takes one value from both the list in the same position and performs the calculation.
number1 = [10, 20, 30] number2 = [15, 25, 35] print(number1) print(number2) print() mul_num = list(map(lambda x, y : x * y, number1, number2)) print(mul_num)
First, x = 10 from number1, y = 15 from number2 list. By adding both of them get 25.
[10, 20, 30] [15, 25, 35] [150, 500, 1050]
reduce and lambda functions fExample
The Python lambda reduce function accepts two values and a list as arguments values and we are using the reduce along with this.
from functools import reduce number = [10, 20, 30, 15, 25, 35, 45] print(number) print("==========") add_num = reduce((lambda x, y : x + y), number) print(add_num)
[10, 20, 30, 15, 25, 35, 45]] ========== 180
First, x = 10, y = 20. Or write it as ((((((10 + 20) + 30) + 15) + 25) + 35) + 45)
Built-in function Example
Until now, we are using the expression to calculate something or perform numerical operations. However, you can use the Python lambda function on string data as well.
In this example, we declared a string list. Next, we used the sorted method to sort the list items. However, we used the sorted key as a expression.
Within this expression, we are using the len method to find the length of each word. It means sorting is done based on the item length.
x = ['apple', 'Mango Fruit', 'Banana', 'oranges', 'cherry','kiwi'] print(x) y = sorted(x, key =lambda a: len(a)) print(y) z = sorted(x, key =lambda a: a.casefold()) print(z)
Python lambda len and casefold functions output.
['apple', 'Mango Fruit', 'Banana', 'oranges', 'cherry', 'kiwi']
['kiwi', 'apple', 'Banana', 'cherry', 'oranges', 'Mango Fruit']
['apple', 'Banana', 'cherry', 'kiwi', 'Mango Fruit', 'oranges']