-4

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 - Slava Ukraini
  • 6,936
  • 1
  • 20
  • 32
6160
  • 1,002
  • 6
  • 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
  • 244,495
  • 58
  • 464
  • 504
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
  • 170,431
  • 36
  • 387
  • 313
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
  • 58,805
  • 11
  • 114
  • 143
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
  • 2,275
  • 1
  • 26
  • 39