239

I'm using Python 3.2. Tried this:

xor = lambda x,y: (x+y)%2
l = reduce(xor, [1,2,3,4])

And got the following error:

l = reduce(xor, [1,2,3,4])
NameError: name 'reduce' is not defined

Tried printing reduce into interactive console - got this error:

NameError: name 'reduce' is not defined


Is reduce really removed in Python 3.2? If that's the case, what's the alternative?

Mateusz Piotrowski
  • 8,029
  • 10
  • 53
  • 79
Sergey
  • 47,222
  • 25
  • 87
  • 129

7 Answers7

342

It was moved to functools.

Ignacio Vazquez-Abrams
  • 776,304
  • 153
  • 1,341
  • 1,358
  • 58
    @julio.alegria: Because [Guido hates it](http://www.artima.com/weblogs/viewpost.jsp?thread=98196). – Ignacio Vazquez-Abrams Dec 31 '11 at 16:55
  • 7
    The article referenced in @IgnacioVazquez-Abrams makes some really good points about how most cases can be written in a more readable fashion. For me, it's by writing `sum(item['key'] for item in list_of_dicts)`. – connorbode Mar 04 '17 at 22:15
  • 6
    This should be in the core language – ctpenrose Aug 10 '20 at 22:07
  • Yet another reason why "python" is not a stable language. First they had python2 and python3 that have intentionally incompatible `print` and now this! – Mikko Rantalainen Jan 25 '23 at 14:53
268

You can add

from functools import reduce

before you use the reduce.

3heveryday
  • 2,697
  • 1
  • 10
  • 4
10

Or if you use the six library

from six.moves import reduce
Azd325
  • 5,752
  • 5
  • 34
  • 57
3

Reduce function is not defined in the Python built-in function. So first, you should import the reduce function

from functools import reduce
Haroon Hayat
  • 329
  • 2
  • 4
2

In this case I believe that the following is equivalent:

l = sum([1,2,3,4]) % 2

The only problem with this is that it creates big numbers, but maybe that is better than repeated modulo operations?

David M
  • 37
  • 1
  • 1
  • Repeated modulo operations are useful when it helps to keep numbers small. Summing numbers won't create large numbers unless you sum A LOT of numbers, so in this case it wouldn't help. Especially since not doing so allows the use of the built-in sum function, which will run much faster than repeated application of a user-defined function – HackerBoss Sep 11 '19 at 03:07
2

Use it like this.

# Use reduce function

from functools import reduce

def reduce_func(n1, n2):

    return n1 + n2


data_list = [2, 7, 9, 21, 33]

x = reduce(reduce_func, data_list)

print(x)
Alex P
  • 1,105
  • 6
  • 18
1

you need to install and import reduce from functools python package