Python Lambda Function

The Python lambda function is anonymous means, a function without a definition keyword and name. To create a Python lambda function, we have to use the lambda keyword. The syntax of the Python lambda expression is

lambda arguments: expression

The Python lambda function accepts any number of arguments. However, Python lambda takes only one expression. For instance, lambda a, b: a + b. Here, a and b are the arguments accepted by the Python lambda function. a + b is the expression.

Python lambda Examples

The following list of examples helps to learn the Python lambda functions.

Python lambda with No Arguments

Use the following Python lambda 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 lambda expression in Python.

# Python Lambda Example

num = lambda: True

print(num())

The Python lambda function with no arguments output

True

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 lambda keyword. After the colon, it is an expression or the functionality it has to perform when we call this anonymous lambda function.

num = lambda x: x + 5

print(num(10))

We passed 10 as the Python argument. 10 + 5 = 15.

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 lambda expression.

add = lambda x, y : x + y

print(add(10, 20))

lambda sum output

30

Generally, we can achieve the same by declaring or creating a Function. This time, we are using the Python lambda expression and regular function. Both give the same result.

add = lambda x, y : x + y
print(add(10, 20))

print("\nResult from a Function")
def add_func(x, y):
   return x + y

print(add_func(10, 20))

Both lambda and regular functions are returning the same result. However, the regular function needs a def keyword, function name, and a return value. Whereas, lambda function does not need any of them. By default, it returns the expression result.

30

Result from a Function
30

Lambda expressions are not about adding two values. We can perform multiplication, subtractions, or any other calculations. Here, we are multiplying two argument values. For better understanding of the lambda expressions, we are placing the regular function as well. Please refer Function in Python

multi = lambda x, y : x * y
print(multi(5, 20))

print("\nResult from a multi Function")
def multi_func(x, y):
    return x * y

print(multi_func(5, 20))
100

Result from a multi Function
100

Python lambda Mulitple Values

In this lambda example, we are using three-arguments. Next, we are multiplying those three argument values.

multi = lambda x, y, z : x * y * z
print(multi(5, 2, 6))

print("\nResult from a multi Function")
def multi_func(x, y, z):
    return x * y * z

print(multi_func(5, 2, 6))

lambda function with three arguments output

60

Result from a multi Function
60

Until now, we used this lambda expression to calculate something and returning results. However, use the print statement to print the lambda output as well. Below lambda code prints Hello World! as an output.

message = lambda: print("Hello World!")

message()

Print lambda function output

Hello World!

We can also achieve the same result by calling that lambda statement with parenthesis.

Python Lambda Example 8

Python lambda Default Argument Values

In this lambda expression example, we assigned default values to all three arguments. Next, we are adding, multiplying, and subtracting them. If we have the default values, we do not have to pass values while calling the Python lambda expression.

# Python Lambda Example

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

sub = lambda x = 10, y = 45: y - x
print(sub()) # 45 - 10
60
6000
35

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

print("Multiplication Values")
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 Default Values 10

Python lambda Without Arguments

If you don’t want to pass any arguments, however, you want to return something from the lambda, then you can use this kind of statement.

We do not have to pass any argument values to call these lambda expressions. Whenever we call them, they return the same result.

add = lambda : 10 + 20
print(add())

print("Multiplication Values")
multi = lambda : 10 * 20
print(multi())

print("Subtraction")
sub = lambda : 225 - 20
print(sub())

Lambda function without arguments output

30
Multiplication Values
200
Subtraction
205

Anonymous Functions using lambda

Python lambda function is powerful when we use this anonymous function inside a function. Here, we declared a function that accepts one argument. Inside the function, we used a Python lambda expression to multiply that value with the unknown number of times.

# Python Anonymous Functions Lambda Example

def new_func(n):
    return lambda x : x * n

number = new_func(2)

print(number(50))

Lambda Anonymous function output 1

100

It calls new_func function where n = 2. It means, function returns lambda x: x * 2. Then, we assigned that value to the number (lambda object)

number = new_func(2)

Next, we called that number with 50 (this is lambda argument value. It means, lambda 50 : 50 * 2 => 100

Calling the lambda function with different values. First with 2, and then with 3.

def new_func(n):
   return lambda x : x * n

number1 = new_func(2)
number2 = new_func(3)

print(number1(50))
print(number2(50))

Lambda Anonymous function output 2

100
150

Lambda with Built-in Functions

In Python, we can use the available Built-in functions along with lambda function.

Python lambda 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 function with a lambda expression. This Python lambda expression checks whether a number is divisible by two or not. Next, the filter function returns all the True values.

number = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15]
print(number)

new_num = list(filter(lambda x : x % 2 == 0, number))
print(new_num)

lambda filter function output

[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15]
[2, 4, 6, 8, 10, 12, 14]

Here, we extended the previous Python lambda example. This lambda code filters and returns the Even Number, Odd Numbers, and Numbers that are divisible by 3. Refer to the Python 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)

num_div_by_3 = list(filter(lambda x : x % 3 == 0, number))
print(num_div_by_3)

Lambda and filter function output 2

[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]
[3, 6, 9, 12, 15]

Lambda map Example

Unlike filter function, map function takes each list item and returns both the True and False values. In this Python lambda example, we used map function 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)

lambda and map function output 1

[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 this Python lambda map function. It takes one individual list item at a time and performs the multiplication. At last, lambda 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)

triple_num = list(map(lambda x : x * 3, number))
print(triple_num)

square_num = list(map(lambda x : x ** 2, number))
print(square_num)

Lambda and map function output 2

[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
[2, 4, 6, 8, 10, 12, 14, 16, 18, 20]
[3, 6, 9, 12, 15, 18, 21, 24, 27, 30]
[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 Python lambda 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()
add_num = list(map(lambda x, y : x + y, number1, number2))
print(add_num)
 
sub_num = list(map(lambda x, y : x - y, number1, number2))
print(sub_num)
 
mul_num = list(map(lambda x, y : x * y, number1, number2))
print(mul_num)

Lambda and map function output 3

[10, 20, 30]
[15, 25, 35]

[25, 45, 65]
[-5, -5, -5]
[150, 500, 1050]

lambda map functions analysis

add_num = list(map(lambda x, y : x + y, number1, number2))

First, x = 10 from number1, y = 15 from number2 list. By adding both of them get 25.

Lambda Reduce Example

The Python lambda reduce function accepts two values and a list as arguments values. Using this reduce function along with the lambda function.

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)
 
sub_num = reduce((lambda x, y : x - y), number)
print(sub_num)
 
mul_num = reduce((lambda x, y : x * y), number)
print(mul_num)

lambda reduce function output

[10, 20, 30, 15, 25, 35, 45]]
==========
180
-160
3543750000

Lambda reduce Analysis

number = [10, 20, 30, 15, 25, 35, 45]
add_num = reduce((lambda x, y : x + y), number)

First, x = 10, y = 20. Or write it as ((((((10 + 20) + 30) + 15) + 25) + 35) + 45)

Lambda Built-in function Example

Until now, we are using the lambda expression to calculate something or performing numerical operations. However, you can use them on string data as well.

In this lambda function example, we declared a string list. Next, we used the sorted function to sort the list items. However, we used the sorted key as a lambda expression. Within this expression, we are using the len function 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)

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']