Reduce is not defined Python
The reduce() function in Python is a function that implements a mathematical technique called ‘folding’ or 'reduction'. In this tutorial, we'll figure out why we get "NameError: the name 'reduce' is not defined", and learn how to fix it. 
What is “reduce is not defined” in Python?
In Python “reduce is not defined” is a NameError that we get when we try to use the reduce() function without importing it.
Why do we get “reduce is not defined” error?
We get a "NameError: name 'reduce' is not defined" when trying to use the reduce() function because the reduce function has been removed from Python3 built-in functions and moved to the “functools” module.
How to fix "NameError: name 'reduce' is not defined"?
There are two simple ways of fixing this error:
Solution 1: import “functools” module
without importing reduce() from 'functools'
def do_math(x, y):
  return x + y
print(reduce(do_math, [5, 5, 3], 7))
after importing reduce() from 'functools'
from functools import reduce
def do_math(x, y):
  return x + y
print("After importing we get -",reduce(do_math, [5, 5, 3], 7))
Output:
name-error-functools after-importing-functools
Solution 2: use the “six” library
importing reduce from "six" libraries
def do_math(x, y):
  return x + y
print(reduce(do_math, [5, 5, 3], 7))
# importing reduce from "six" libraries
from six.moves import reduce
def do_math(x, y):
  return x + y
print("Using six library we get -",reduce(do_math, [5, 5, 3], 7))
Output:
name-error-functools after-six-library
Conclusion In this tutorial, we figured out where the "NameError: name 'reduce' is not defined" is coming from and covered two ways to fix this error.
更多推荐

所有评论(0)