30

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?

Karl Knechtel
  • 62,466
  • 11
  • 102
  • 153
anhldbk
  • 4,559
  • 5
  • 29
  • 37
  • 4
    One of the reasons `reduce` was moved out of the built-ins was because it was frequently being used for addition, where `sum` is preferable (in this case, you could just do `sum(range(1, 11))`, or `sum(xrange(1, 11))` in Python 2). Note also that there is an `add` function equivalent to yours in the standard library: `operator.add`. – James Apr 19 '12 at 11:00

2 Answers2

61

I'm going to guess that:

  1. You are using Python 3, and
  2. You are following a tutorial designed for Python 2.

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))
Greg Hewgill
  • 951,095
  • 183
  • 1,149
  • 1,285
10

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))
chim
  • 8,407
  • 3
  • 52
  • 60