Lambda functions are similar to regular functions in Python. Lambda functions are small (usually one line) and anonymous functions.
Examine the code below. The function multiply_by_2()
can be implemented in two ways: As a regular function and as a lambda function.
# multiply_by_2 defined as a regular function
def multiply_by_2(num):
return num * 2
# multiply_by_2 defined as lambda function
multiply_by_2 = lambda num: num * 2
Syntax for creating a lambda expression is as follows:
lambda argument(s) : expression
You can also define lambda functions that can take more than one argument.
multiply_numbers = lambda num1, num2: num1 * num2
print(multiply_numbers(3, 5)) # 15
Lambda functions are important because they are used with Python’s built-in functions like map()
, filter()
, etc.
Lambda with filter() Function
In the code below, filter()
function takes a lambda function as the first argument. This lambda function returns true if it takes an even number as argument, it returns false if it takes odd number as argument. filter()
function filters the original list and returns another list that contains only even numbers.
numbers = [1, 4, 5, 7, 9, 12, 15, 16, 18, 21, 22]
even_numbers = list(filter(lambda x: (x % 2) == 0, numbers))
print(even_numbers) # [4, 12, 16, 18, 22]
Lambda with map() Function
Similar to filter()
function, map()
function also takes a lambda as the first argument. The map()
function takes an iterable (like list) and applies the given lambda function to each element in the iterable. Then, it returns another iterable containing lambda applied elements.
In the sample code below, the lambda function takes an argument and returns the value multiplied by 2. The map()
function applies this lambda function to each element in the original list.
numbers = [1, 2, 3, 4, 5]
multiplied_numbers = list(map(lambda x: x * 2, numbers))
print(multiplied_numbers) # [2, 4, 6, 8, 10]