Python Reduce Function Tutorial – Complete Guide

If you’re venturing into the world of Python, it’s impossible to bypass its long list of built-in functions. One key function that often stumps beginners is the reduce function. A feature of Python’s functools module, reduce is a tool that simplifies iterative processes. It might be challenging at first, but mastering this function will add a valuable another piece to your Python programming toolkit.

What is the Python Reduce Function?

Reduce is a function that essentially reduces a list to a single output. It does this by applying a specific function in a cumulative way to pairs of values in a list, in order to combine all list elements.

When working with lists, you might often need to perform a common operation on all elements and get a single output. For example, you may need to multiply all elements, or add them together. The reduce function shines in these scenarios, providing a neat and efficient solution.

Like other Python built-ins, reduce assists in writing cleaner and more efficient code. These high-level functions, inspired by mathematical concepts, also step towards more advanced Python features and concepts. Mastering this function opens a pathway to functional programming, a paradigm where functions are first-class citizens. It’s a stepping stone on your road to Python mastery, whether you’re a game developer, data scientist or a web developer.

CTA Small Image
FREE COURSES AT ZENVA
LEARN GAME DEVELOPMENT, PYTHON AND MORE
ACCESS FOR FREE
AVAILABLE FOR A LIMITED TIME ONLY

How to Use Reduce Function in Python

Let’s start by importing the reduce function from the functools module:

from functools import reduce

Now, let’s create a simple list:

my_list = [2, 4, 6, 8]

Our first task is to find the product of all numbers in the list. Here’s how to use reduce:

product = reduce((lambda x, y: x * y), my_list)
print(product)

This outputs 384, which is the product of all elements in the list.

Using Reduce with Different Functions

Let’s continue experimenting. This time, we want to find the sum of all elements in the list:

sum = reduce((lambda x, y: x + y), my_list)
print(sum)

This outputs 20, the sum of all elements in the list.

We can use reduce with a custom function as well. Let’s say we want to find the maximum element in the list:

def max(a,b):
    if a>b:
        return a
    else:
        return b

maximum = reduce(max, my_list)
print(maximum)

This gives us 8, which is the maximum number in the list.

We can even use reduce for more advanced operations, like finding the factorial of a number:

number = 5
factorial = reduce(lambda x, y: x*y, range(1,number+1))
print(factorial)

This gives us 120, which is the factorial of 5. As you can see, reduce is a versatile function that can significantly optimize our Python code.

More Examples with the Python Reduce Function

Let’s explore more examples to illustrate the versatility of the Python reduce function.

Finding the Minimum

Apart from finding the maximum, we can use reduce to find the minimum element in a list:

def min(a,b):
    if a<b:
        return a
    else:
        return b

minimum = reduce(min, my_list)
print(minimum)

This gives us 2, the minimum number in our list.

Combining Strings

Reduce is not limited to numbers. We can use it to combine strings as well:

strings_list = ["Zenva", "Academy", "Python", "Tutorial"]
sentence = reduce(lambda x,y: x+" "+y, strings_list)
print(sentence)

This prints “Zenva Academy Python Tutorial”, combining all strings in the list into a sentence.

Counting Occurrences

We can also use reduce to count the occurrences of a certain element in a list:

numbers_list = [1, 1, 2, 3, 4, 4, 4, 5]
count = reduce(lambda x, y: x + 1 if y == 4 else x, numbers_list, 0)
print(count)

This prints ‘3’, the number of times ‘4’ appears in the list.

Merging Dictionaries

Even more advanced uses are possible. For example, we can merge dictionaries using reduce:

dict_list = [{'a': 1}, {'b': 2}, {'c': 3}, {'d': 4}]
merged_dict = reduce(lambda a, b: {**a, **b}, dict_list)
print(merged_dict)

This will output {‘a’: 1, ‘b’: 2, ‘c’: 3, ‘d’: 4}, merging all dictionaries into one.

Through these examples we can see the potential of reduce; it’s a highly adaptable function that can be used across a broad range of data types, from numbers to strings to dictionaries. It’s an indispensable tool on your journey toward Python proficiency. At Zenva, we believe in giving you the tools and understanding to work with such powerful functions, and take your coding skills to the next level.

Where to Go Next?

After learning about the Python reduce function, you may be wondering where to take your Python journey next. At Zenva, we have a comprehensive roadmap for learners at every stage of their coding journey.

One of the best ways to continue mastering Python is by enrolling in our Python Mini-Degree program. This comprehensive course builds a solid foundation in Python programming and goes beyond the basics, covering topics like algorithms, object-oriented programming, game development, and app development.

The Python Mini-Degree isn’t just about learning, it’s about doing. As a student, you’ll get hands-on experience creating games, algorithms, and real-world applications, resulting in a diverse portfolio of Python projects.

Our courses feature interactive lessons, quizzes, and live coding exercises, allowing you to learn by doing. Our instructors, certified by Unity Technologies and CompTIA, bring extensive experience to the table, imparting essential skills and knowledge that you can apply immediately.

If you’re looking for a more broad collection of Python courses, you can explore our Python Courses. These courses are designed to cater to learners at different stages of their Python journey.

Conclusion

Python’s reduce function is a clear illustration of how Python incorporates powerful features into simple syntax. What might have taken multiple lines of code can be condensed into a single, readable line, contributing to cleaner and more efficient code.

Getting the hang of reduce, like any other programming concept, comes with practice. Don’t shy away from experimenting with it in your projects and exercises. In fact, you’ll find this function quite handy in your Python journey, which you’re hopefully pursuing with us at Zenva. If you’re ready to take the next big step, do check out our Python Mini-Degree. Let’s continue to tackle Python’s capabilities together, building a strong foundation for your future coding endeavors.

Did you come across any errors in this tutorial? Please let us know by completing this form and we’ll look into it!

FREE COURSES
Python Blog Image

FINAL DAYS: Unlock coding courses in Unity, Godot, Unreal, Python and more.