Python Lambda Functions
In this tutorial, we'll study anonymous functions, commonly called lambda functions. We'll understand what they are, how to execute them, and their syntax.
What are Lambda Functions in Python?
Lambda Functions in Python are anonymous functions, implying they don't have a name. The def keyword is needed to create a typical function in Python, as we already know. We can also use the lambda keyword in Python to define an unnamed function.
Syntax of Python Lambda Function
lambda arguments: expression
This function accepts any count of inputs but only evaluates and returns one expression.
Lambda functions can be used whenever function arguments are necessary. In addition to other forms of formulations in functions, it has a variety of applications in certain coding domains. It's important to remember that according to syntax, lambda functions are limited to a single statement.
Example of Lambda Function in Python
An example of a lambda function that adds 4 to the input number is shown below.
Code
# Code to demonstrate how we can use a lambda function
add = lambda num: num + 4
print( add(6) )
Output:
10
Code
def add( num ):
return num + 4
print( add(6) )
Output:
10
What's the Distinction Between Lambda and Def Functions?
Let's glance at this instance to see how a conventional def defined function differs from a function defined using the lambda keyword. This program calculates the reciprocal of a given number:
Code
# Python code to show the reciprocal of the given number to highlight the difference between def() and lambda().
def reciprocal( num ):
return 1 / num
lambda_reciprocal = lambda num: 1 / num
# using the function defined by def keyword
print( "Def keyword: ", reciprocal(6) )
# using the function defined by lambda keyword
print( "Lambda keyword: ", lambda_reciprocal(6) )
Output:
Def keyword: 0.16666666666666666
Lambda keyword: 0.16666666666666666
The reciprocal() and lambda_reciprocal() functions act similarly and as expected in the preceding scenario. Let's take a closer look at the sample above:
Both of these yield the reciprocal of a given number without employing Lambda. However, we wanted to declare a function with the name reciprocal and send a number to it while executing def. We were also required to use the return keyword to provide the output from wherever the function was invoked after being executed.
Using Lambda: Instead of a "return" statement, Lambda definitions always include a statement given at output. The beauty of lambda functions is their convenience. We need not allocate a lambda expression to a variable because we can put it at any place a function is requested.
Using Lambda Function with filter()
The filter() method accepts two arguments in Python: a function and an iterable such as a list.
The function is called for every item of the list, and a new iterable or list is returned that holds just those elements that returned True when supplied to the function.
Here's a simple illustration of using the filter() method to return only odd numbers from a list.
Code
# Code to filter odd numbers from a given list
list_ = [34, 12, 64, 55, 75, 13, 63]
odd_list = list(filter( lambda num: (num % 2 != 0) , list_ ))
print(odd_list)
Output:
[55, 75, 13, 63]
Using Lambda Function with map()
A method and a list are passed to Python's map() function.
The function is executed for all of the elements within the list, and a new list is produced with elements generated by the given function for every item.
The map() method is used to square all the entries in a list in this example.
Code
#Code to calculate the square of each number of a list using the map() function
numbers_list = [2, 4, 5, 1, 3, 7, 8, 9, 10]
squared_list = list(map( lambda num: num ** 2 , numbers_list ))
print( squared_list )
Output:
[4, 16, 25, 1, 9, 49, 64, 81, 100]
Using Lambda Function with List Comprehension
We'll apply the lambda function combined with list comprehension and lambda keyword with a for loop in this instance. We'll attempt to print the square of numbers in the range 0 to 11.
Code
#Code to calculate square of each number of list using list comprehension
squares = [lambda num = num: num ** 2 for num in range(0, 11)]
for square in squares:
print( square(), end = " ")
Output:
0 1 4 9 16 25 36 49 64 81 100
Use of lambda in list comprhension
numbers = [1, 2, 3, 4, 5]
data=["even" if num %2 ==0 else "odd" for num in numbers]
print(data)
using lamda
numbers = [1, 2, 3, 4, 5]
data = [(lambda num: "even" if num % 2 == 0 else "odd")(num) for num in numbers]
print(data)
# Output: ['odd', 'even', 'odd', 'even', 'odd']
numbers = [1, 2, 3, 4, 5]
squared_values = [(lambda x: x ** 2)(num) for num in numbers]
print(squared_values)
# Output: [1, 4, 9, 16, 25]
Use of Nested lambda in list comprhension
use list comprhension
numbers = [1, 2, 3, 4, 5]
result = [(num ** 2) + 10 for num in numbers]
print(result)
# Output: [11, 14, 19, 26, 35]
Using Lambda
numbers = [1, 2, 3, 4, 5]
result = [(lambda x: (lambda y: y + 10)(x ** 2))(num) for num in numbers]
print(result)
This list comprehension applies the first lambda function (lambda x: (lambda y: y + 10)(x ** 2)) to each element in numbers, where the inner lambda function takes the square of the element and adds 10.
Top comments (0)