0

I need to know if any element in a list meets a certain criteria. To do so, I want to use a generator expression inside an any() function, but the output seems to misbehave:

>>> x
[0, 0, 0]
>>> gen = (z==1 for z in x)
>>> any(gen)
True

If I instead use a list, I get the right answer:

>>> x
[0, 0, 0]
>>> com = [z==1 for z in x]
>>> any(com)
False

I've tried this on two different Windows 7 computers, one with python 2.7.2 and one with 2.7.3. Both return the wrong answer. I had someone try it on their machine which has python 2.7.5 and he got the right answer. Does anybody know what's going on here?

Cascadian
  • 93
  • 1
  • 5
  • 12
    Let me guess. You're using NumPy, and for some reason you or a tool you're using has done `from numpy import *`, causing `any` to be `numpy.any`. – user2357112 Jun 22 '14 at 21:01
  • 2
    @user2357112: There should be a "crystal ball" badge for this kind of thing. I hope you're right. – Tim Pietzcker Jun 22 '14 at 21:03
  • 2
    @user2357112, would numpy any not return a generator object? – Padraic Cunningham Jun 22 '14 at 21:03
  • @user2357112 I'll have to verify, but I'm quite confident this is it. I'm using python(x,y), which automatically imports numpy and a few other scientific modules. Is there a way for me to specify that I want the non-numpy any()? – Cascadian Jun 22 '14 at 21:07
  • @Cascadian Import Python's `any()` using: `from __builtin__ import any` – Ashwini Chaudhary Jun 22 '14 at 21:10
  • @PadraicCunningham: You're right. Maybe the actual test used `if any(gen):` rather than directly showing `any(gen)`. – user2357112 Jun 22 '14 at 21:12
  • @200OK thank you! That did the trick. Also, it looks like this is a known issue. Look here for more info: Thanks folks! http://stackoverflow.com/questions/16334860/why-do-numpy-all-and-any-give-wrong-results-if-you-use-generator-expressions – Cascadian Jun 22 '14 at 21:18
  • @user2357112 Who's going to win the World Cup? – Burhan Khalid Jun 22 '14 at 21:27
  • @user2357112 Thank you! My notebook was working before, and then I started it from inside PyCharm. Apparently PyCharm imports everything from NumPy. – orodbhen Feb 02 '18 at 17:12

2 Answers2

0

The above statement returns the correct answer for both Python 3.x and 2.x on my machine, so the causes of the above must be from some currently unknown other factor, with the above comments attempting to poke something out of this mystery. The productive thing to do will be to check your Python is running clean without any third-patry packages, and if it is, perhaps strip it down and work your way back up until you reach the problem package.

idiot.py
  • 388
  • 2
  • 7
-2

Your first example returns "False" in Python 3.4. So it looks proper and good, like it should.

Looks like a bug in old Python versions then or some maybe it was intended back in the old Python 2 days.

nilshi
  • 504
  • 1
  • 6
  • 16