coolpy coolpy - 4 months ago 11
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")
else:
print(y)


It keeps printing
y is not in range
.

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




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

Answer

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')
else:
    print(y)

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