Python Tutorial - Master Python Programming For Beginners from Scratch

  • Home
  • Getting Started
  • Basics
  • OOP
  • Advanced Python
  • Tkinter
Home » Python Basics » How to Use the Python Reduce() function to Reduce a List into a Single Value

How to Use the Python Reduce() function to Reduce a List into a Single Value

Summary: in this tutorial, you’ll learn how to use the Python reduce() function to process a list.

Reducing a list

Sometimes, you want to reduce a list to a single value. For example, suppose that you have a list of numbers:

scores = [75, 65, 80, 95, 50]
Code language: Python (python)

And to calculate the sum of all elements in the scores list, you can use a for loop like this:

scores = [75, 65, 80, 95, 50] total = 0 for score in scores: total += score print(total)
Code language: Python (python)

Output:

365
Code language: Python (python)

In this example, we have reduced the whole list into a single value, which is the sum of all elements from the list.

Introduction the Python reduce() function

Python offers a function called reduce() that allows you to reduce a list in a more concise way.

Here is the syntax of the reduce() function:

reduce(fn,list)
Code language: Python (python)

The reduce() function applies the fn function of two arguments cumulatively to the items of the list, from left to right, to reduce the list into a single value.

Unlike the map() and filter() functions, the reduce() isn’t a built-in function in Python. In fact, the reduce() function belongs to the functools module.

To use the reduce() function, you need to import it from the functools module using the following statement at the top of the file:

from functools import reduce
Code language: Python (python)

Note that you’ll learn more about modules and how to use them in the later tutorial.

The following illustrates how to use the reduce() function to calculate the sum of elements of the scores list:

from functools import reduce def sum(a, b): print(f"a={a}, b={b}, {a} + {b} ={a+b}") return a + b scores = [75, 65, 80, 95, 50] total = reduce(sum, scores) print(total)
Code language: Python (python)

Output:

a=75, b=65, 75 + 65 = 140 a=140, b=80, 140 + 80 = 220 a=220, b=95, 220 + 95 = 315 a=315, b=50, 315 + 50 = 365 365
Code language: Python (python)

As you can see clearly from the output, the reduce() function cumulatively adds two elements of the list from left to right and reduces the whole list into a single value.

To make the code more concise, you can use a lambda expression instead of defining the sum() function:

from functools import reduce scores = [75, 65, 80, 95, 50] total = reduce(lambda a, b: a + b, scores) print(total)
Code language: Python (python)

Summary

  • Use the Python reduce() function to reduce a list into a single value.
  • Was this tutorial helpful ?
  • YesNo
Previous How to Filter List Elements in Python
Next Python List Comprehensions

Getting Started

  • What is Python
  • Install Python
  • Setup VS Code for Python
  • Develop Python Hello World Program

Python Fundamentals

  • Python Syntax
  • Variables
  • Strings
  • Numbers
  • Boolean
  • Constants
  • Comments
  • Type Conversion

Control Flow

  • if…else
  • Ternary Operator
  • for Loop
  • while Loop
  • break
  • continue
  • pass

Functions

  • Python Functions
  • Default Parameters
  • Keyword Arguments
  • Recursive Functions
  • Lambda Expressions
  • Function Docstrings

Python List

  • List
  • Tuple
  • Sorting a List in Place: sort()
  • Sorting a List: sorted()
  • Slicing a List: [::]
  • Unpacking a List
  • Iterating over a List: for loop
  • Finding Index of an Element: index()
  • Iterables
  • Transform List Elements: map()
  • Filtering List Elements: filter()
  • Reducing List Elements: reduce()
  • List Comprehensions

Python Dictionary

  • Dictionary
  • Dictionary Comprehension

Python Set

  • Set
  • Set Comprehension
  • Union of Sets
  • Intersection of Sets
  • Difference between Sets
  • Symmetric Difference of Sets
  • Subset
  • Superset
  • Disjoint Sets

Exception Handling

  • try…except
  • try…except…finally
  • try…except…else

Python Loop with Else Clause

  • for…else
  • while…else
  • do…while Emulation

More on Functions

  • Unpacking Tuples
  • The *args Parameters
  • The **kwargs Parameters
  • Partial Functions

Modules

  • Modules
  • Module Search Path
  • Python __name__
  • Packages

File I/O

  • Reading a Text File
  • Writing to a Text File
  • Creating a Text File
  • Checking If a File Exists
  • Reading from a CSV File
  • Writing to a CSV File

Managing Third-party Packages

  • Python Package Index (PyPI) & PIP
  • Python Virtual Environments
  • Install pipenv on Windows
  • Using pipenv Tool

About pythontutorial.net

Pythontutorial.net helps you master Python programming from scratch fast.

Site Links

  • Home
  • Contact
  • About
  • Privacy Policy

Recent Python Tutorials

  • Tkinter StringVar
  • Tkinter PhotoImage
  • Tkinter OptionMenu
  • Tkinter ScrolledText
  • How to Change the Appearances of Widgets Dynamically Using Ttk Style map() Method

Python References

  • Python String Methods
  • Python MySQL
  • Python PostgreSQL
  • Python Oracle
  • Python SQLite

Copyright © 2021 · by pythontutorial.net. All rights reserved. Log in