0

I try to check if two chars 'x' and '+' are in the array ['+', '-']. I get "True" as the result of this check, even though 'x' is obviously not in the array.

if 'x' and '+' in ['+', '-']:
    print('True')
else:
    print('False')

I also tried to check this:

if 'x' and '-' in ['x', 'y']:
    print('True')
else:
    print('False')

This works correctly, 'False' gets printed. What is the mistake?

  • See also the other Q&As linked there: https://stackoverflow.com/questions/15112125/how-to-test-multiple-variables-for-equality-against-a-single-value, https://stackoverflow.com/questions/6159313/how-to-test-the-membership-of-multiple-values-in-a-list – mkrieger1 May 31 '23 at 10:56

1 Answers1

0

You are getting this because the first part of both the expressions is True.

'+' in ['+', '-']

True

'-' in ['x', 'y']

False

if 'x' and '+' in ['+', '-']:

#if True('x' is considered Boolean True as it is non-zero) AND True

#True

Take an example this:

if 0 and '+' in ['+', '-']:
    print('True')
else:
    print('False')

output
False

#reason 0 is considered False in Boolean and other things are True, so it will be

False AND True

False
Talha Tayyab
  • 8,111
  • 25
  • 27
  • 44
  • In your second example, the last part won't even get evaluated, as False and whatever is already decided by the first False. – Thierry Lathuille May 31 '23 at 11:07
  • Its boolean `FALSE` AND `TRUE`. Gave this example to OP to make them understand that `if x` is `True` in their example if we put `if False` then there will be different result. – Talha Tayyab May 31 '23 at 11:30