×

Python Tutorial

Python Basics

Python I/O

Python Operators

Python Conditions & Controls

Python Functions

Python Strings

Python Modules

Python Lists

Python OOPs

Python Arrays

Python Dictionary

Python Sets

Python Tuples

Python Exception Handling

Python NumPy

Python Pandas

Python File Handling

Python WebSocket

Python GUI Programming

Python Image Processing

Python Miscellaneous

Python Practice

Python Programs

Python reduce() with Lambda Function

Last Updated : April 25, 2025

The reduce() function applies on each element of an iterable collection and returns the reduced (based on applied calculation through the function) value.

The lambda function is an anonymous function - that means the function which does not have any name.

Implementing reduce() with lambda function

You can implement the reduce() function with a lambda expression to perform cumulative operations on a list, such as calculating the sum or product of all elements.

The following is the syntax of using reduce() with a lambda function in Python:

reduce(lambda arguments: expression, iterable)

Example Using reduce() and lambda

The following example demonstrates how to use reduce() with a lambda function to calculate the sum of all elements in a list:

from functools import reduce

def add(data):
    s=0
    for n in data:
        s=s+n
    return s

# list of integers	
fibo=[0,1,1,2,3,5,8,13,21,34,55]
print("Orignal List  :",fibo)

# using reduce and lambda
s=reduce(lambda a,b:a+b,fibo)
print("Sum = ",s)

The output of the above code will be:

Orignal List  : [0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55]
Sum =  143

Explanation

  • The list fibo contains Fibonacci numbers.
  • The reduce() applies the lambda function cumulatively to the list.
  • The lambda function lambda a, b: a + b adds two elements at a time.
  • The result is the total sum of all elements in the list.

Python reduce() with Lambda Exercise

Select the correct option to complete each statement about using reduce() with lambda functions in Python.

  1. The reduce() function is available in the ___ module.
  2. reduce(lambda x, y: x + y, [1, 2, 3, 4]) will return:
  3. The reduce() function applies the lambda function in a ___ manner.

Advertisement
Advertisement

Comments and Discussions!

Load comments ↻


Advertisement
Advertisement
Advertisement

Copyright © 2025 www.includehelp.com. All rights reserved.