-5

This will probably be a dumb question, but why does this piece of code behave like this?

>>> test = ['aaa','bbb','ccc']
>>> if 'ddd' or 'eee' in test:
...     print True
... 
True
>>> 

I was expecting nothing printed on the stdio, because none of the strings in the IF statement are in the list.

Am I missing something?

Lennart
  • 6,000
  • 1
  • 18
  • 31
6160
  • 990
  • 5
  • 15

4 Answers4

7

if 'ddd' or 'eee' in test

is evaluated as:

if ('ddd') or ('eee' in test):

as a non-empty string is always True, so or operations short-circuits and returns True.

>>> bool('ddd')
True

To solve this you can use either:

if 'ddd' in test or 'eee' in test:

or any:

if any(x in test for x in ('ddd', 'eee')):

Ashwini Chaudhary
  • 232,417
  • 55
  • 437
  • 487
4

Your test should be

if 'ddd' in test or 'eee' in test:

In the code you currently have 'ddd' string is evaluated as boolean and since it is not empty its bool value is True

Vladimir
  • 169,112
  • 36
  • 383
  • 312
0

You are missing something here:

if 'ddd' or 'eee' in test:

is equivalent to:

if ('ddd') or ('eee' in test):

And thus that will always be True, because 'ddd' is considered True.


You want:

if any(i in test for i in ('ddd', 'eee')):
TerryA
  • 56,204
  • 11
  • 116
  • 135
0
>>> if 'ddd'
...     print True

will print

True

So you should write :

>>> if 'ddd' in test or 'eee' in test:
...     print True

in order to get the result you want.

Fabrice Jammes
  • 1,463
  • 15
  • 26