1. What is a lambda function?
A lambda function in Python is an anonymous function, meaning it is a function without a name. In Python, we use the keyword ‘lambda‘ to define a lambda function. The syntax for a lambda function is as follows:
lambda arguments: expression
Lambda functions can have any number of parameters but only one expression. The expression is calculated, evaluated, and then returned. An example of a lambda function is as follows:
# lambda function
double = lambda x: x * 2
print(double(5))
x ="Gochocit.com"
# lambda function gets pass to print
y = lambda x : print(x)
y(x)
Result:
10
Gochocit.com
2. Using Lambda Function in Python
A lambda function often uses in another function to help perform a task. Lambda functions are also often used as arguments for other functions such as filter()
, map()
, etc.
Lambda Function is Often Inside a Function
def power(n):
return lambda a : a ** n
# set n = 2
# base = lambda a : a**2
# returned to base
base = power(2)
print("8 powerof 2 = ", base(8))
base = power(5)
print("8 powerof 5 = ", base(8))
Result:
8 powerof 2 = 64
8 powerof 5 = 32768
Using lambda Function with filter() Function
The filter()
function in Python takes a function and a list as arguments. The filter()
function iterates through all the items in the list and filters out the items that satisfy a particular condition.
# numbers list
numbers = [1, 5, 4, 6, 8, 11, 3, 12]
# filter out only the even items from numbers list
new_numbers = list(filter(lambda x: (x%2 == 0) , numbers))
print(new_numbers)
Result:
[4, 6, 8, 12]
In the above example, the filter()
function helps to filter out even numbers from a list.
Using Lambda Function with map() Function
The map()
function in Python takes a function and a list as arguments. The map()
function iterates through each item in the list. While iterating, the map()
function performs calculations on each item using the function argument and returns a new list with the calculated items.
# numbers list
numbers = [1, 5, 4, 6, 8, 11, 3, 12]
# double each item in numbers list using map()
new_numbers = list(map(lambda x: x * 2 , numbers))
print(new_numbers)
Result:
[2, 10, 8, 12, 16, 22, 6, 24]
In the above example, the map()
function helps to double all the items in a list.