coolpy coolpy - 1 year ago 68
Python Question

If statement with composite condition to validate condition against each item in a list

I found a similar question here but the answers don't seem to apply to my issue.

Here is my code:

y = 3
list1 = [1,2,3,4,5]

if y != 0 or y != list1:
print("y is not in range")

It keeps printing
y is not in range

My goal is to check if
does not equal to
or if
does not equal to any item in the list.

I understand that the above
should be an
, I'm specifically interested in how to check in the condition of
being contained in the list.

Answer Source

You want to check that y is different from 0 AND not in the list:

if y != 0 and y not in list1:

Using or means that one of the conditions is sufficient, so since y != 0 it returns True without going to y != list1 which would always return False because an int is not a list, you have to use in in that case.

If you really want to use an or then you what you want:

if not (y == 0 or y in list1):
    print('y not in range')

Rememer the De Morgan laws:

not (y == 0 or y in list1) == (not y == 0) and (not y in list1) == y != 0 and y not in list1
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download