Lambda Functions
Learning objective
• What is Lambda Function
• Map function
• Filter function
• Reduce function
What is Lambda Function
• Small, anonymous function defined using the lambda keyword.
• Used for creating small, one-time-use functions without the need
to formally define a function using the def keyword.
• They are often used for short operations that don't require a full
function definition.
• Lambda forms can take any number of arguments but return just
one value in the form of an expression.
Simplest form of Lambda Functions
Syntax:
lambda arguments: expression
---------------------------------------
addition = lambda a, b: a + b
print(addition(40,50))
cube = lambda n1 : n1 * n1 * n1
print(cube(10))
Example of Regular and Lambda Function
Program to add 2 numbers using Program to add 2 numbers using
Function lambda Function
def sum(n1,n2): sum = lambda n1,n2: (n1+n2)
s=n1+n2
return s x=int(input("Enter the number:"))
y=int(input("Enter the number:"))
x=int(input("Enter the number: ")) print(sum(x,y))
y=int(input("Enter the number: "))
print(sum(x,y))
Example of Regular and Lambda Function
# Regular function
def square(x):
return x ** 2
# Equivalent lambda function
lambda_square = lambda x: x ** 2
print(f"Reqular function result: {square(5)} ")
print(f"Lambda function result: {lambda_square(5)}")
Lambda Function with multiple arguments
#Lambda Function with Multiple Arguments
add = lambda x, y: x + y
print(add(3, 4)) # Output: 7
#Lambda function with a condition to check if a number is even or odd
is_even = lambda x: "Even Number" if x % 2 == 0 else "Odd Number”
# Testing the lambda function
print(is_even(4))
print(is_even(7))
map() Function
• Built-in function that allows you to apply a specified function to all
the items in an input list (or any iterable) and return an iterator that
produces the results.
• The basic syntax of the map() function is as follows:
map(function, iterable, ...)
• function: A function to apply to each item in the iterable.
• iterable: An iterable (e.g., a list, tuple, or other iterable).
Squaring each element in a list using regular
function
def square(x):
return x ** 2
numbers = [1, 2, 3, 4, 5]
squared_numbers = map(square, numbers)
print(list(squared_numbers))
Squaring each element in a list using lambda
function
numbers = [1, 2, 3, 4, 5]
squared_numbers_lambda = map(lambda x: x ** 2, numbers)
print(list(squared_numbers_lambda))
Example: Converting strings to uppercase
words = ["apple", "banana", "cherry"]
uppercase_words = map(str.upper, words)
print(list(uppercase_words))
Example: Adding corresponding elements of 2
lists
list1 = [1, 2, 3, 4]
list2 = [5, 6, 7, 8]
sum_of_lists = map(lambda x, y: x + y, list1, list2)
print(list(sum_of_lists))
filter() Function
• Built-in function that allows you to construct an iterator from
elements of an iterable for which a function returns True.
• Used to apply a function to each element of an iterable (like a list
or tuple) and return another iterable containing just the elements
for which the function brings True back.
filter(function, iterable)
• A function that tests whether each element of an iterable returns
True or False.
• iterable: An iterable (e.g., a list, tuple, etc.).
Filtering even numbers from a list
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
def is_even(x):
return x % 2 == 0
even_numbers = filter(is_even, numbers)
print(list(even_numbers))
Using lambda with filter
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
even_numbers = list(filter(lambda x: x % 2 == 0, numbers))
print(even_numbers)
Filtering words with length greater than 4
words = ["apple", "banana", "kiwi", "pear", "orange"]
def is_long(word):
return len(word) > 4
long_words = filter(is_long, words)
print(list(long_words))
Filter out negative numbers from a list
numbers = [ 1, -2, 3, -4, 5, -6 ]
result = list(filter(lambda x: x >= 0, numbers))
print(result)
reduce() function
• Built-in function that is part of the functools module.
• It is used to apply a binary function (a function taking two
arguments) cumulatively to the items of an iterable, from left to
right, so as to reduce the iterable to a single cumulative result.
• The basic syntax of the reduce() function is as follows:
functools.reduce(function, iterable)
function: A binary function that takes two arguments.
iterable: An iterable (e.g., a list, tuple, or other iterable).
Summing up elements in a list
from functools import reduce
numbers = [1, 2, 3, 4, 5]
sum_result = reduce(lambda x, y: x + y, numbers)
print(sum_result)
Calculating the product elements in a list
from functools import reduce
numbers = [2, 3, 4, 5]
product_result = reduce(lambda x, y: x * y, numbers)
print(product_result)
Concatenating strings in a list
from functools import reduce
words = ["Hello", " ", "World", "!"]
concatenated_result = reduce(lambda x, y: x + y, words)
print(concatenated_result)
Finding the maximum element in a list
from functools import reduce
numbers = [4, 2, 8, 6, 7]
max_result = reduce(lambda x, y: x if x > y else y, numbers)
print(max_result)
reduce() function
• In each example, the reduce() function applies the specified
binary function (lambda x, y: ...) to the elements of the iterable,
accumulating a single result.
• The initializer is optional and not used in these examples.
• The reduce() function is especially useful when you need to
perform cumulative operations on the elements of a sequence.
Try to do it yourself:
• Create a list product numbers [10, 50, 55, 40, 9, 7, 55, 10, 40, 44]
• Add the quantity of 10 to numbers using map() with lambda
function
• Filter the even quantities using filter() with lambda function
• Sum list of numbers using reduce() with lambda function to
accumulate values
Expected output:
Original Product quantity list: [10, 50, 55, 40, 9, 7, 55, 10, 40, 44]
[20, 60, 65, 50, 19, 17, 65, 20, 50, 54]
[10, 50, 40, 10, 40, 44]
The total product quantity is: 320
# create a list of numbers from 1 to 20
my_product_list = [10, 50, 55, 40, 9, 7, 55, 10, 40, 44]
print(f"Original Product quantity list: {my_product_list}")
# Add the quantity of 10 to numbers using map() with lambda function
sq_numbers = list(map(lambda x: x + 10, my_product_list))
print(sq_numbers)
# Filter the even quantities using filter() with lambda function
even_nos = list(filter(lambda x: x % 2 == 0, my_product_list))
print(even_nos)
# sum my_product_list using reduce() with lambda function to accumulate values
from functools import reduce
totalprod = reduce(lambda x, y: x + y, my_product_list)
print(f"The total product quantity is: {totalprod}")
You must have learnt:
• What is Lambda Function
• Map function
• Filter function
• Reduce function