Question

[Solved] 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?

Enquirer: Sergey

||

Solution #1:

It was moved to functools.

Solution #2:

You can add

from functools import reduce

before you use the reduce.

Respondent: 3heveryday

Solution #3:

Or if you use the six library

from six.moves import reduce
Respondent: Azd325

Solution #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?

Respondent: David M

Solution #5:

you need to install and import reduce from functools python package

Respondent: Jesvin Vijesh S

The answers/resolutions are collected from stackoverflow, are licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0 .

Most Popular

To Top
India and Pakistan’s steroid-soaked rhetoric over Kashmir will come back to haunt them both clenbuterol australia bossier man pleads guilty for leadership role in anabolic steriod distribution conspiracy