1

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!

jacob
  • 828
  • 8
  • 13
  • 1
    I don't think `any([-0.676, -0.676, -0.676]) >= 1` is doing what you think it's doing. Perhaps you meant: `any(x >= 1 for x in [-0.676, -0.676, -0.676])`? – pault Feb 23 '18 at 21:25
  • Why its *not expected*? – heemayl Feb 23 '18 at 21:26
  • 3
    You gave a link to the documentation for truth value testing, but it appears you didn't read it. – John Y Feb 23 '18 at 21:28
  • Total newbie here. Sorry. I see now why everything I was doing is expected. Thank you for everyone's time and extremely fast responses. – jacob Feb 23 '18 at 21:32

2 Answers2

1

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)
khelwood
  • 55,782
  • 14
  • 81
  • 108
  • Yes, I just realized this pretty much 30 seconds after posting. Sorry, and thank you for your time. Total newbie here. – jacob Feb 23 '18 at 21:28
1

Please read the documentation:

any(iterable)

Return True if any element of the iterable is true. If the iterable is empty, return False. Equivalent to:

def any(iterable):
    for element in iterable:
        if element:
            return True
    return False

All your any() expression listed will return True, and you are comparing True with 1, that is True.

Community
  • 1
  • 1
llllllllll
  • 16,169
  • 4
  • 31
  • 54
  • Thank you, I had a different idea of what an iterable was. Though I just discovered the python glossary, so I will make my best effort to not let this happen again with other terms. Still working on my coding vocabulary. Thanks for your time. – jacob Feb 23 '18 at 21:42