Search code examples
pythonpython-3.xany

Python any() function does not act as expected for list of negative numbers


I am trying to compare a list of numbers in an if statement with the any() function. I am using python 3.6 in Spyder. The code in question is:

if any(lst) >= 1:
    do_some_stuff

lst is actually generated by list(map(my_func, other_lst)) but after diagnosing my problem I get two behaviors as shown below with my actual lst passed to the any() function:

any([1.535, 1.535, 1.535]) >= 1
>>True

Which is expected.

any([-0.676, -0.676, -0.676]) >= 1
>>True

Which is not expected.

I've delved deeper and found that any number I can put in lst that is less than 0 yields True in my if statement. Also, converting the 1 to a float doesn't help. After reading "truth value testing", this post, and extensive time trying to learn the behavior within my program, I am at a loss. Please help, I am pretty new to python. Thanks!


Solution

  • You are comparing the wrong thing. You are comparing the result of any to 1.

    any(mylist) will return true if any element of the list is nonzero. True is greater than or equal to 1.

    So this

    any(mylist)>=1
    

    is equivalent to just

    any(mylist)
    

    What you mean is

    any(x>=1 for x in mylist)