Last modified: Mar 03, 2025 By Alexander Williams

Fix Python NameError: Name 'reduce' Not Defined

If you've encountered the Python NameError: name 'reduce' is not defined, don't worry. This error is common and easy to fix. Let's explore the cause and solution.

What Causes the NameError: Name 'reduce' Not Defined?

The error occurs when you try to use the reduce function without importing it first. In Python 3, reduce was moved to the functools module.

If you're using Python 2, reduce is a built-in function. However, in Python 3, you must import it explicitly.

How to Fix the NameError: Name 'reduce' Not Defined

To fix this error, you need to import the reduce function from the functools module. Here's how:


from functools import reduce

# Example usage of reduce
numbers = [1, 2, 3, 4]
result = reduce(lambda x, y: x + y, numbers)
print(result)  # Output: 10
    

In this example, reduce is imported from functools. The function is then used to sum the elements in the list.

Common Mistakes to Avoid

One common mistake is forgetting to import reduce in Python 3. Another is assuming reduce is still a built-in function.

Always check your Python version and ensure you import the necessary modules. For more on fixing similar errors, see our guide on Fix Python NameError: Name 're' Not Defined.

Example with Output

Let's look at another example to understand the error and its solution better.


# This will raise NameError: name 'reduce' is not defined
numbers = [1, 2, 3, 4]
result = reduce(lambda x, y: x * y, numbers)
print(result)
    

NameError: name 'reduce' is not defined
    

To fix this, import reduce from functools:


from functools import reduce

numbers = [1, 2, 3, 4]
result = reduce(lambda x, y: x * y, numbers)
print(result)  # Output: 24
    

Conclusion

The NameError: name 'reduce' is not defined is a common issue in Python 3. The solution is simple: import reduce from the functools module.

By understanding the cause and applying the correct import statement, you can avoid this error. For more tips on fixing Python errors, check out our guide on Fix Python NameError: Name 'sys' Not Defined.

Happy coding!