2

In a python console (using 2.7) if I put in the following code:

vals = [1.2e-5, 1.5e-5, 3.2e-5, 4.5e-5]
for val in vals: print val < 0.001,

The output is True True True True as expected.

But! Here is my problem, if I try all(vals) < 0.001 it returns false?

Is it the number formatting giving it problems or something else? If I do this again but replace the vals list with vals = [2,2,2,2] and check for < 3 I get the desired output both ways!

EDIT Helpful answers, it is interesting to note that all([0.1, 0.1, 0.1]) evaluates to True, but 0.1 == True evaluates to False? What's up with this? Is it that a "nonzero" value will evaluate to True but is not actually "True"?

rhawker
  • 43
  • 5
  • 1
    Check [How Python's any and all functions work?](http://stackoverflow.com/questions/19389490/how-pythons-any-and-all-functions-work) – sam Oct 19 '15 at 01:14
  • @sam2090 what's crazy is that I had actually read that, and I still couldn't see what I was doing wrong!! Guess it comes from staring at something for too long. All sorted now! – rhawker Oct 19 '15 at 01:20

2 Answers2

2

all(vals) checks whether all the values are boolean True (i.e., nonzero). That is True. True is not less than 0.001.

I think you want something like all(val < 0.001 for val in vals).

BrenBarn
  • 242,874
  • 37
  • 412
  • 384
  • You are correct that I have used it incorrectly, but can you add any information regarding the edit I added to my question? – rhawker Oct 19 '15 at 01:33
2

Your usage is wrong. all(x < 0.001 for x in vals) should be okay.

all(vals) < 0.001 will check whether all vals is truthy, then compare the True or False you get as the result with 0.001, which is weird.

Amadan
  • 191,408
  • 23
  • 240
  • 301
  • You are correct that I have used it incorrectly, but can you add any information regarding the edit I added to my question? – rhawker Oct 19 '15 at 01:33
  • 1
    `int(True) == 1`; `int(False) == 0`. Consequently, `True == 1` and `False == 0`. How that relates to `< 0.001` should be obvious now :) – Amadan Oct 19 '15 at 01:36
  • @Amadan: you don't even need the `int` calls, since `bool` is a subclass of `int`. `True == 1` is `True`. – Blckknght Oct 19 '15 at 01:42
  • @Blckknght: yeah; I wrote it so that the point was lost; but I meant that if you evaluate `int(True)`, you can literally see in the console that it prints `1`. – Amadan Oct 19 '15 at 01:44
  • @Blckknght cool to know it is a subclass of int, definitely makes things obvious. Also thanks for the clarification Amadan – rhawker Oct 19 '15 at 01:51