0

I have an if statement which always returns as true even if it is not. I have a global list : NUMBERS_LIST = []

Numbers get added to it via an API call, that works fine.

When it does the following:

def func():
    if 8 or 9 in NUMBER_LIST:
        return true
    elif 1 or 2 in NUMBER_LIST:
        return true

But for some reason, it always returns true on the first if statement, even if NUMBER_LIST = [1]

I debugged my program and can see that NUMBER_LIST does contain 1, it's type is int. I tried doing int(8), converting both types to str but that did not fix my issue. When I debugged and step through the program, it doesn't really tell me much, I am using Pycharm.

trigster
  • 87
  • 9
  • This probably should be closed as a duplicate; I answered only because the amount of confusion over how the `or` operator behaves in situations like these indicates that the similarity of `x or y == z` and `x or y in z` could be overlooked. (My vote would immediately close the question, hence my not voting.) – chepner Oct 21 '19 at 16:02
  • @NChauhan Kind of the same idea, but I don't think that would make a good duplicate in this case. – chepner Oct 21 '19 at 16:04
  • @chepner I think the duplicate I have suggested does answer the question as some answers point out you would use `any(x in list for x in values_to_check)` to see if any of the values are in the list. – N Chauhan Oct 21 '19 at 16:07
  • 1
    It doesn't address what is wrong with the OP's code in the first place, though, which I think is important. The duplicate suggested by Ture Pålsson does. – chepner Oct 21 '19 at 16:09

1 Answers1

6

or does not distribute. What you have written is not equivalent to

if 8 in NUMBER_LIST or 9 in NUMBER_LIST:

which is what you want, but to

if 8 or (9 in NUMBER_LIST):

Since 8 is a truthy value, the containment operation is never evaluated.

chepner
  • 497,756
  • 71
  • 530
  • 681