Maarten
Maarten

Reputation: 253

Python any() condition not returning correct output

I cannnot find out why any() is not returning True here. I think it may have something to do with numpy.any instead of the builtin any() function, as is suggested here. However, I've also tried calling any as __builtins __.any, but it still returns False.

import numpy as np

import numpy as np
VCI=20
anom_con = [10,20,35,50]
print VCI<anom_con[3]
print VCI<any(anom_con)

returns:

True
False

Interestingly, I am also using any() elsewhere in my code, and it works fine there:

z=-0.668
z_con = [-2,-1.5,-1,1,1.5,2]
print z < any(z_con)

returns:

True

Upvotes: 0

Views: 47

Answers (1)

DeepSpace
DeepSpace

Reputation: 81654

any works as expected, just not as you expected it to work.

any returns True as soon as it finds an element which evaluates to True. In case of numbers it means it will return True as soon as it finds a non-zero element.

What you meant to write is any(num > VCI for num in anom_con) in the first example and any(num > z for num in z_con) in the second example.

The fact that

z = -0.668
z_con = [-2,-1.5,-1,1,1.5,2]
print z < any(z_con)

outputs a "correct" output is purely coincidental. It prints True because:

  1. any(z_con) evaluates to True (because z_con has at least one non-zero number)
  2. z < True evaluates to True because True has the underlying value of 1, and -0.668 < 1 is True.

Upvotes: 3

Related Questions