The Wayback Machine - https://web.archive.org/web/20241122153324/https://www.geeksforgeeks.org/reduce-in-python/
Open In App

reduce() in Python

Last Updated : 20 Jun, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

The reduce(fun,seq) function is used to apply a particular function passed in its argument to all of the list elements mentioned in the sequence passed along.This function is defined in “functools” module.

Working :  

  • At first step, first two elements of sequence are picked and the result is obtained.
  • Next step is to apply the same function to the previously attained result and the number just succeeding the second element and the result is again stored.
  • This process continues till no more elements are left in the container.
  • The final returned result is returned and printed on console.
Python3
# python code to demonstrate working of reduce()

# importing functools for reduce()
import functools

# initializing list
lis = [1, 3, 5, 6, 2]

# using reduce to compute sum of list
print("The sum of the list elements is : ", end="")
print(functools.reduce(lambda a, b: a+b, lis))

# using reduce to compute maximum element from list
print("The maximum element of the list is : ", end="")
print(functools.reduce(lambda a, b: a if a > b else b, lis))

Output
The sum of the list elements is : 17
The maximum element of the list is : 6

 

Using Operator Functions


reduce() can also be combined with operator functions to achieve the similar functionality as with lambda functions and makes the code more readable.

Python3
# python code to demonstrate working of reduce()
# using operator functions

# importing functools for reduce()
import functools

# importing operator for operator functions
import operator

# initializing list
lis = [1, 3, 5, 6, 2]

# using reduce to compute sum of list
# using operator functions
print("The sum of the list elements is : ", end="")
print(functools.reduce(operator.add, lis))

# using reduce to compute product
# using operator functions
print("The product of list elements is : ", end="")
print(functools.reduce(operator.mul, lis))

# using reduce to concatenate string
print("The concatenated product is : ", end="")
print(functools.reduce(operator.add, ["geeks", "for", "geeks"]))

Output
The sum of the list elements is : 17
The product of list elements is : 180
The concatenated product is : geeksforgeeks

reduce() vs accumulate() 

Both reduce() and accumulate() can be used to calculate the summation of a sequence elements. But there are differences in the implementation aspects in both of these.  

  • reduce() is defined in “functools” module, accumulate() in “itertools” module.
  • reduce() stores the intermediate result and only returns the final summation value. Whereas, accumulate() returns a iterator containing the intermediate results. The last number of the iterator returned is summation value of the list.
  • reduce(fun, seq) takes function as 1st and sequence as 2nd argument. In contrast accumulate(seq, fun) takes sequence as 1st argument and function as 2nd argument.
Python3
# python code to demonstrate summation
# using reduce() and accumulate()

# importing itertools for accumulate()
import itertools

# importing functools for reduce()
import functools

# initializing list
lis = [1, 3, 4, 10, 4]

# printing summation using accumulate()
print("The summation of list using accumulate is :", end="")
print(list(itertools.accumulate(lis, lambda x, y: x+y)))

# printing summation using reduce()
print("The summation of list using reduce is :", end="")
print(functools.reduce(lambda x, y: x+y, lis))

Output
The summation of list using accumulate is :[1, 4, 8, 18, 22]
The summation of list using reduce is :22

                                                                                             reduce() function with three parameters

Reduce function i.e. reduce() function works with 3 parameters in python3 as well as for 2 parameters. To put it in a simple way reduce() places the 3rd parameter before the value of the second one, if it’s present. Thus, it means that if the 2nd argument is an empty sequence, then 3rd argument serves as the default one. 

 Here is an example :(This example has been take from the  functools.reduce() documentation includes a Python version of the function:

Python
# Python program to  illustrate sum of two numbers.
def reduce(function, iterable, initializer=None):
    it = iter(iterable)
    if initializer is None:
        value = next(it)
    else:
        value = initializer
    for element in it:
        value = function(value, element)
    return value

# Note that the initializer, when not None, is used as the first value instead of the first value from iterable , and after the whole iterable.
tup = (2,1,0,2,2,0,0,2)
print(reduce(lambda x, y: x+y, tup,6))

# This code is contributed by aashutoshjha

Output
15


 This article is contributed by Manjeet Singh(S.Nandini).

reduce() in Python – FAQs

What is the reduce method in a list? 

The reduce function is used to apply a function of two arguments cumulatively to the items of a list (or any iterable), from left to right, so as to reduce the iterable to a single value. It’s not a method of the list but a function in the functools module.

What is the return value of reduce() function?

The return value of the reduce() function is a single value, which is the result of the cumulative application of the provided function to the elements of the iterable.

Which module should we import to use the reduce() function?

To use the reduce() function, you need to import it from the functools module.

How to import the reduce function from the functools module?

You can import the reduce function from the functools module using the following import statement:

from functools import reduce

What is the difference between reduce and accumulate?

  • Purpose: Reduces an iterable to a single value by cumulatively applying a function.
  • Return Value: A single value.
  • Usage Example:
from functools import reduce
# Example: Sum of all elements
numbers = [1, 2, 3, 4]
result = reduce(lambda x, y: x + y, numbers)
print(result) # Output: 10
  • reduce:
    • accumulate:
      • Purpose: Computes accumulated results of applying a function (like cumulative sum) and returns an iterator with intermediate results.
      • Return Value: An iterator containing the accumulated results.
      • Module: itertools
      • Usage Example:
    from itertools import accumulate
    # Example: Cumulative sum of all elements
    numbers = [1, 2, 3, 4]
    result = list(accumulate(numbers, lambda x, y: x + y))
    print(result) # Output: [1, 3, 6, 10]


    Previous Article
    Next Article

    Similar Reads

    Python | Find the Number Occurring Odd Number of Times using Lambda expression and reduce function
    Given an array of positive integers. All numbers occur even number of times except one number which occurs odd number of times. Find the number in O(n) time & constant space. Examples: Input : [1, 2, 3, 2, 3, 1, 3] Output : 3 We have existing solution for this problem please refer Find the Number Occurring Odd Number of Times link. we will solv
    1 min read
    Tips to reduce Python object size
    We all know a very common drawback of Python when compared to programming languages such as C or C++. It is significantly slower and isn't quite suitable to perform memory-intensive tasks as Python objects consume a lot of memory. This can result in memory problems when dealing with certain tasks. When the RAM becomes overloaded with tasks during e
    4 min read
    How to reduce dimensionality on Sparse Matrix in Python?
    A matrix usually consists of a combination of zeros and non-zeros. When a matrix is comprised mostly of zeros, then such a matrix is called a sparse matrix. A matrix that consists of maximum non-zero numbers, such a matrix is called a dense matrix. Sparse matrix finds its application in high dimensional Machine learning and deep learning problems.
    3 min read
    Count operations of the given type required to reduce N to 0
    Given an integer n. The task is to count the number of operations required to reduce n to 0. In every operation, n can be updated as n = n - d where d is the smallest prime divisor of n.Examples: Input: n = 5 Output: 1 5 is the smallest prime divisor, thus it gets subtracted and n gets reduced to 0.Input: n = 25 Output: 11 5 is the smallest prime d
    4 min read
    Tensorflow | tf.data.Dataset.reduce()
    With the help of tf.data.Dataset.reduce() method, we can get the reduced transformation of all the elements in the dataset by using tf.data.Dataset.reduce() method. Syntax : tf.data.Dataset.reduce() Return : Return combined single result after transformation. Note : These given examples will demonstrate the use of new version of tensorflow 2.0, so
    1 min read
    Reduce the array by deleting elements which are greater than all elements to its left
    Given an array arr[] of N integers, the task is to delete the element from the given array if element to it's left is smaller than it. Keep on deleting the elements from the array until no element has a smaller adjacent left element. Print the resultant array after above operation. Examples: Input: arr[] = {2, 4, 1, 3, 4} Output: 2 1 Explanation: S
    5 min read
    How to Fix: TypeError: cannot perform reduce with flexible type
    In this article we will discuss TypeError: cannot perform reduce with flexible type and how can we fix it. This error may occur when we find the mean for a two-dimensional NumPy array which consists of data of multiple types. Dataset in use: Student ID Student Name Branch Marks 101 Harry CSE 87 102 Ron ECE 88 103 Alexa CSE 72 When we create this ta
    2 min read
    Build a URL Size Reduce App with Django
    Django is a high-level Python web framework that encourages rapid development and clean, pragmatic design. In this article, we will learn to build a URL shortener using Django. A URL shortener is used to reduce the size of long URLs. Short URLs are better for sharing purposes. In this article, we will use Bitly API to shorten our URL. For this, we
    5 min read
    Important differences between Python 2.x and Python 3.x with examples
    In this article, we will see some important differences between Python 2.x and Python 3.x with the help of some examples. Differences between Python 2.x and Python 3.x Here, we will see the differences in the following libraries and modules: Division operatorprint functionUnicodexrangeError Handling_future_ modulePython Division operatorIf we are p
    5 min read
    Reading Python File-Like Objects from C | Python
    Writing C extension code that consumes data from any Python file-like object (e.g., normal files, StringIO objects, etc.). read() method has to be repeatedly invoke to consume data on a file-like object and take steps to properly decode the resulting data. Given below is a C extension function that merely consumes all of the data on a file-like obj
    3 min read
    Python | Add Logging to a Python Script
    In this article, we will learn how to have scripts and simple programs to write diagnostic information to log files. Code #1 : Using the logging module to add logging to a simple program import logging def main(): # Configure the logging system logging.basicConfig(filename ='app.log', level = logging.ERROR) # Variables (to make the calls that follo
    2 min read
    Python | Add Logging to Python Libraries
    In this article, we will learn how to add a logging capability to a library, but don’t want it to interfere with programs that don’t use logging. For libraries that want to perform logging, create a dedicated logger object, and initially configure it as shown in the code below - Code #1 : C/C++ Code # abc.py import logging log = logging.getLogger(_
    2 min read
    Python | Index of Non-Zero elements in Python list
    Sometimes, while working with python list, we can have a problem in which we need to find positions of all the integers other than 0. This can have application in day-day programming or competitive programming. Let's discuss a shorthand by which we can perform this particular task. Method : Using enumerate() + list comprehension This method can be
    6 min read
    MySQL-Connector-Python module in Python
    MySQL is a Relational Database Management System (RDBMS) whereas the structured Query Language (SQL) is the language used for handling the RDBMS using commands i.e Creating, Inserting, Updating and Deleting the data from the databases. SQL commands are case insensitive i.e CREATE and create signify the same command. In this article, we will be disc
    2 min read
    Python - Read blob object in python using wand library
    BLOB stands for Binary Large OBject. A blob is a data type that can store binary data. This is different than most other data types used in databases, such as integers, floating point numbers, characters, and strings, which store letters and numbers. BLOB is a large complex collection of binary data which is stored in Database. Basically BLOB is us
    2 min read
    twitter-text-python (ttp) module - Python
    twitter-text-python is a Tweet parser and formatter for Python. Amongst many things, the tasks that can be performed by this module are : reply : The username of the handle to which the tweet is being replied to. users : All the usernames mentioned in the tweet. tags : All the hashtags mentioned in the tweet. urls : All the URLs mentioned in the tw
    3 min read
    Reusable piece of python functionality for wrapping arbitrary blocks of code : Python Context Managers
    Context Managers are the tools for wrapping around arbitrary (free-form) blocks of code. One of the primary reasons to use a context manager is resource cleanliness. Context Manager ensures that the process performs steadily upon entering and on exit, it releases the resource. Even when the wrapped code raises an exception, the context manager guar
    7 min read
    Creating and updating PowerPoint Presentations in Python using python - pptx
    python-pptx is library used to create/edit a PowerPoint (.pptx) files. This won't work on MS office 2003 and previous versions. We can add shapes, paragraphs, texts and slides and much more thing using this library. Installation: Open the command prompt on your system and write given below command: pip install python-pptx Let's see some of its usag
    4 min read
    Python Debugger – Python pdb
    Debugging in Python is facilitated by pdb module (python debugger) which comes built-in to the Python standard library. It is actually defined as the class Pdb which internally makes use of bdb(basic debugger functions) and cmd (support for line-oriented command interpreters) modules. The major advantage of pdb is it runs purely in the command line
    5 min read
    Filter Python list by Predicate in Python
    In this article, we will discuss how to filter a python list by using predicate. Filter function is used to filter the elements in the given list of elements with the help of a predicate. A predicate is a function that always returns True or False by performing some condition operations in a filter method Syntax: filter(predicate, list) where, list
    2 min read
    Python: Iterating With Python Lambda
    In Python, the lambda function is an anonymous function. This one expression is evaluated and returned. Thus, We can use lambda functions as a function object. In this article, we will learn how to iterate with lambda in python. Syntax: lambda variable : expression Where, variable is used in the expressionexpression can be an mathematical expressio
    2 min read
    Python Value Error :Math Domain Error in Python
    Errors are the problems in a program due to which the program will stop the execution. One of the errors is 'ValueError: math domain error' in Python. In this article, you will learn why this error occurs and how to fix it with examples. What is 'ValueError: math domain error' in Python?In mathematics, we have certain operations that we consider un
    4 min read
    Creating Your Own Python IDE in Python
    In this article, we are able to embark on an adventure to create your personal Python Integrated Development Environment (IDE) the usage of Python itself, with the assistance of the PyQt library. What is Python IDE?Python IDEs provide a characteristic-rich environment for coding, debugging, and going for walks in Python packages. While there are ma
    3 min read
    GeeksforGeeks Python Foundation Course - Learn Python in Hindi!
    Python - it is not just an ordinary programming language but the doorway or basic prerequisite for getting into numerous tech domains including web development, machine learning, data science, and several others. Though there's no doubt that the alternatives of Python in each of these respective areas are available - but the dominance and popularit
    5 min read
    Python math.sqrt() function | Find Square Root in Python
    sqrt() function returns square root of any number. It is an inbuilt function in Python programming language. In this article, we will learn more about the Python Program to Find the Square Root. sqrt() Function We can calculate square root in Python using the sqrt() function from the math module. In this example, we are calculating the square root
    3 min read
    Python Image Editor Using Python
    You can create a simple image editor using Python by using libraries like Pillow(PIL) which will provide a wide range of image-processing capabilities. In this article, we will learn How to create a simple image editor that can perform various operations like opening an image, resizing it, blurring the image, flipping and rotating the image, and so
    13 min read
    Python | Set 4 (Dictionary, Keywords in Python)
    In the previous two articles (Set 2 and Set 3), we discussed the basics of python. In this article, we will learn more about python and feel the power of python. Dictionary in Python In python, the dictionary is similar to hash or maps in other languages. It consists of key-value pairs. The value can be accessed by a unique key in the dictionary. (
    5 min read
    Learn DSA with Python | Python Data Structures and Algorithms
    This tutorial is a beginner-friendly guide for learning data structures and algorithms using Python. In this article, we will discuss the in-built data structures such as lists, tuples, dictionaries, etc, and some user-defined data structures such as linked lists, trees, graphs, etc, and traversal as well as searching and sorting algorithms with th
    15+ min read
    Why we write #!/usr/bin/env python on the first line of a Python script?
    The shebang line or hashbang line is recognized as the line #!/usr/bin/env python. This helps to point out the location of the interpreter intended for executing a script, especially in Unix-like operating systems. For example, Linux and macOS are Unix-like operating systems whose executable files normally start with a shebang followed by a path to
    2 min read
    Setting up ROS with Python 3 and Python OpenCV
    Setting up a Robot Operating System (ROS) with Python 3 and OpenCV can be a powerful combination for robotics development, enabling you to leverage ROS's robotics middleware with the flexibility and ease of Python programming language along with the computer vision capabilities provided by OpenCV. Here's a step-by-step guide to help you set up ROS
    3 min read
    Article Tags :
    Practice Tags :
    three90RightbarBannerImg