NameError: name 'reduce' is not defined in Python

PythonReducePython 3.2

Python Problem Overview


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?

Python Solutions


Solution 1 - Python

Solution 2 - Python

You can add

from functools import reduce

before you use the reduce.

Solution 3 - Python

Or if you use the six library

from six.moves import reduce

Solution 4 - Python

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?

Solution 5 - Python

you need to install and import reduce from functools python package

Solution 6 - Python

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

from functools import reduce

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionSergeyView Question on Stackoverflow
Solution 1 - PythonIgnacio Vazquez-AbramsView Answer on Stackoverflow
Solution 2 - Python3heverydayView Answer on Stackoverflow
Solution 3 - PythonAzd325View Answer on Stackoverflow
Solution 4 - PythonDavid MView Answer on Stackoverflow
Solution 5 - PythonJesvin Vijesh SView Answer on Stackoverflow
Solution 6 - PythonHaroon HayatView Answer on Stackoverflow