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?

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

It was moved to functools.

Method 2

You can add

from functools import reduce

before you use the reduce.

Method 3

Or if you use the six library

from six.moves import reduce

Method 4

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?

Method 5

you need to install and import reduce from functools python package

Method 6

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

from functools import reduce


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x