Sergey
Sergey

Reputation: 49728

NameError: name 'reduce' is not defined in Python

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?

Upvotes: 244

Views: 186070

Answers (7)

Prabhat Pal
Prabhat Pal

Reputation: 31

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)

Upvotes: 3

Haroon Hayat
Haroon Hayat

Reputation: 435

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

from functools import reduce

Upvotes: 4

user13769010
user13769010

Reputation:

you need to install and import reduce from functools python package

Upvotes: 1

Azd325
Azd325

Reputation: 6120

Or if you use the six library

from six.moves import reduce

Upvotes: 10

3heveryday
3heveryday

Reputation: 2787

You can add

from functools import reduce

before you use the reduce.

Upvotes: 277

David M
David M

Reputation: 37

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?

Upvotes: 2

Ignacio Vazquez-Abrams
Ignacio Vazquez-Abrams

Reputation: 798376

It was moved to functools.

Upvotes: 348

Related Questions