Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 628
Sergey Avatar asked Oct 21 '22 10:10

Sergey


People also ask

How do I fix NameError is not defined in Python?

The Python "NameError: name is not defined" occurs when we try to access a variable or function that is not defined or before it is defined. To solve the error, make sure you haven't misspelled the variable's name and access it after it has been declared.

How do you reduce a name error in Python?

The Python "NameError: name 'reduce' is not defined" occurs when we use the reduce() function without importing it first. To solve the error, import the function from the functools module before using it - from functools import reduce . Here is an example of how the error occurs. Copied!

What does reduce () do in Python?

Python's reduce() is a function that implements a mathematical technique called folding or reduction. reduce() is useful when you need to apply a function to an iterable and reduce it to a single cumulative value.

How do you correct a NameError in Python?

To specifically handle NameError in Python, you need to mention it in the except statement. In the following example code, if only the NameError is raised in the try block then an error message will be printed on the console.


1 Answers

It was moved to functools.

like image 335
Ignacio Vazquez-Abrams Avatar answered Oct 24 '22 00:10

Ignacio Vazquez-Abrams