When I try this code in Python 3.x, I get an error message that says "NameError: global name 'reduce' is not defined".
def main():
def add(x,y): return x+y
reduce(add, range(1, 11))
if __name__=='__main__':
main()
Why?
When I try this code in Python 3.x, I get an error message that says "NameError: global name 'reduce' is not defined".
def main():
def add(x,y): return x+y
reduce(add, range(1, 11))
if __name__=='__main__':
main()
Why?
I'm going to guess that:
The reduce
function, since it is not commonly used, was removed from the built-in functions in Python 3. It is still available in the functools
module, so you can do:
import functools
def main():
def add(x,y): return x+y
functools.reduce(add, range(1, 11))
Also
# Import reduce from functools
from functools import reduce
Allows you to use reduce
as though it were a built in function.
def main():
def add(x,y): return x+y
reduce(add, range(1, 11))