Register Login

Lambda Function in Python

Updated Jan 18, 2022

Lambda function in Python is an anonymous or also known as unknown function meaning that the function does not have a name. They reduce down the code size and makes it easy for the programmer to do faster software development.

The syntax for defining lambda function is,

lambda arguments: expression

Characteristics of Lambda Function:

Lambda function takes an unlimited number of arguments however has only one expression. This expression returns the result when the lambda function is called. 2. Since it contains only one expression which returns the result by default, it does not require the return statement.

Let us consider an example of lambda function:

res = lambda x: x + 5
print(res(10))

Here,

lambda is the keyword,
x is an argument, and
x+5 is lambda expression.

res = lambda  x : x + 5
print(res(10))

Difference between lambda functions and user-defined functions

Lambda functions are anonymous functions which mean a function is defined using a lambda keyword and without a name, whereas a user-defined function is defined using a def keyword and has a function name.

Lambda functions with List comprehension List comprehension is a well-ordered way to create a new list from an existing list.

Example:

numbers=[1,2,3]
square_numbers=[number ** 2 for number in numbers]
print(square_numbers)

Output:

If you want to define a function that returns the square of numbers, in this case, you can define a lambda function that returns the square of the number and get the result in a list using list comprehension. This helps to optimize the code in one line.

Program:

res = [(lambda x: x*x) (x) for x in range(5) ]
print(res)

Output:



Explanation:

Here we have created a variable res and use the lambda function and nested the operations that will iterate (x being the counter variable) till the range 5. Finally, we are using the print() function to display the result.

Lambda functions with if-else statement

The lambda expression can also include conditional statements such as if-else, hence a lambda function returns the result based on the satisfying condition.

For example:

test = lambda x: True if (x > 10) else False
print(test(55))
print(test(8))

Output:

Lambda functions with multiple if-else statement

Similar to lambda with if-else condition, you can implement lambda with multiple if-else conditions as well, as shown in the following code block:

test = lambda x : 'Between 1 to 5' if (x > 1 and x < 5) else 'Equal to 5' if x == 5 else 'Greater than 5'
print(test(2))
print(test(5))
print(test(20))

Output:

Lambda functions with map()

The map() is used to apply a function to each element in the iterable, which returns a map object.

For example:

def square(n): 
  return n * n 
numbers = (1, 2, 3, 4) 
result = map(square, numbers) 
print(tuple(result)) 

Output:

In the above example, programmers can also use the lambda function to optimize the code and since it is required for a short period of time.

Something like this:

numbers = (1, 2, 3, 4)
result = map(lambda x : x*x, numbers)
print(tuple(result))

Output:

Lambda functions with filter()

The filter() applies the function to each element in the iterable and filters the iterable.

Program:

def even(num): 
	if (num%2 == 0): 
		return num 
sequence = [2, 5, 7, 12, 16, 18, 3, 33, 25] 
filtered = filter(even, sequence) 
print('The filtered numbers are:') 
for num in filtered: 
	print(num)

Output:

Explanation:

This program is not an optimized one. Here we have created a user-defined function “even” where we are checking whether the numbers/elements in the sequence list are even or odd. We take the filtered elements and used the for loop to display them through print() function.

Programmers can optimize the above code using lambda function as shown below:

Program:

sequence = [2, 5, 7, 12, 16, 18, 3, 33, 25]
res = filter(lambda x: x % 2 == 0, sequence)
print(list(res))

Output:

Explanation:

Here, we have created a list name sequence and placed in 9 elements. Then, we will use the filter() that comprises of the lambda. This lambda will execute the x and check whether x divided by zero results to 0 or not. All the elenets get fetched from the sequence list. Finally, at the time of display, the print() function is provided with the res that is converted to a list and hence we can see the [] box brackets in the output.

Lambda functions with reduce()

The reduce() function is defined in functools module. It is used to apply a function to all the iterable elements and returns a result.

Program:

import functools 
from functools import reduce 
li = [1, 3, 5, 6, 2] 
def add(a, b): 
	res=0 
	for num in li: 
		res+=num 
	return res 
addition = reduce(add, li) 
print(addition)  

Output:

Explanation:

In this program, we have to import the reduce from  functools module. Next, we will create a list and initialize it with 5 elements. We then create a user defined function add() and initialize a variable res with 0. Then, within that function, we will create a for loop that will iterate all the elements of li list and add the value of num to the res variable. Finally, the function will return the res variable.

Outside the function, we will call the reduce() and pass the function name (add), and the list (li). The calculated value will get stored in the addition variable that will be displayed using the print() function.

The above code can be implemented using lambda() as shown below:

import functools 
from functools import reduce 
li = [1, 3, 5, 6, 2] 
res = functools.reduce(lambda a, b: a+b, li)
print(res) 

Output:

Explanation:

Here we have to first import the functools module and then from functools, we have to specifically import the reduce. Next, we will create a list and initialize it with 5 elements. We then, use the functools.reduce() and pass the lambda expression within it to add all the elements of the list using the two local variables a and b. Finally we print the value that is summed up in the res.

Conclusion:

This tutorial taught us how Lambda is different from a user-defined function and how the lambda function can be used with other functions. Lambdas with filter can help reduce down the code with slight efficiency. Programmers should now be able to use lambda() in case a function. Complexity-wise, it helps in easy interpretation but makes it easy once programmers get used to it.


×