Table of Contents
In this Python tutorial, learn to take a look at anonymous functions with lambda. Anonymous functions are functions that are not associated with a name. For instance, when we use def(), it defines a function with a keyword associated to it. But, the lambda function creates anonymous functions.
Python lambda Syntax
A lambda function can unlimited arguments but the expression must only be one, which will be returned after evaluation. Wherever objects are required, the lambda function could ultimately replace those objects if only a single expression.
The syntax for the lambda function is shown as below:
lambda arguments: expression
def() function and lambda function
Let’s take a look at comparing a def() function to a lambda function with the same expression to calculate the square root of a single number.
Input:
import math def defined_square(y): return math.sqrt(y); lambda_square = lambda x: math.sqrt(x) print(f"This is the square root using a defined function: {defined_square(5)} ") print(f"This is the square root using a lambda function: {lambda_square(5)} ")
Output:
This is the square root using a defined function: 2.23606797749979 This is the square root using a lambda function: 2.23606797749979
lambda() and filter() function – filter(lambda())
The Python filter() function creates a list of elements. This is perfect for sequencing elements when True is returned from the function.
Input:
number_range = range(5, 25) greater_than_zero = list(filter(lambda x: x > 0, number_range)) print(f"These are all of the numbers greater than zero: {greater_than_zero} ")
Output:
These are all of the numbers greater than zero: [5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24]
The built-in lambda function resembles a for loop but is a bit faster in comparison. This could make a significant impact with a large amount of code for performance optimization.
lambda() and map() function – map(lambda())
The map() function applies each item in an list with a function as an argument. A list must be called with the lambda function, which will return a new list with the modified data.
Input:
number_range = range(1, 5) squared_number_range = list(map(lambda x: x**2, number_range)) print(f"These are all of the numbers squared: {squared_number_range} ")
Output:
These are all of the numbers squared: [1, 4, 9, 16]
lambda() and reduce() function – reduce(lambda())
The reduce() function helps when performing list computation and returning the result. If we were looking to compute a list of integers and a new reduced result will be returned with a repetitive operations of the list pairs.
Input:
from functools import reduce number_range_mul = reduce((lambda x, y: x * y), range(1, 8)) print(f"This is the result of reducing the numbers range with multiplication: {number_range_mul} ")
Output:
This is the result of reducing the numbers range with multiplication: 5040