NameError: name 'reduce' is not defined in Python
Asked Answered
P

7

244

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?

Peay answered 31/12, 2011 at 16:25 Comment(0)
S
346

It was moved to functools.

Shawna answered 31/12, 2011 at 16:27 Comment(4)
@julio.alegria: Because Guido hates it.Shawna
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).Shaeshaef
This should be in the core languageCompton
Yet another reason why "python" is not a stable language. First they had python2 and python3 that have intentionally incompatible print and now this!Phyllous
K
275

You can add

from functools import reduce

before you use the reduce.

Kokaras answered 1/4, 2015 at 8:59 Comment(1)
The previous user has already answered the question and the answer is same as that of his answerMittiemittimus
M
10

Or if you use the six library

from six.moves import reduce
Monto answered 10/11, 2015 at 20:15 Comment(0)
A
4

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

from functools import reduce
Antoniettaantonin answered 26/3, 2022 at 19:43 Comment(0)
T
3

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)
Thunderstruck answered 18/11, 2022 at 9:5 Comment(0)
E
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?

Emplace answered 26/3, 2015 at 1:35 Comment(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 functionThilde
D
1

you need to install and import reduce from functools python package

Deoxygenate answered 18/9, 2020 at 8:50 Comment(0)

© 2022 - 2025 — McMap. All rights reserved.