0

I'm attempting to check if a string element(s) are contained in a list.

Code :

if('a' in ['notin']):
    print('test')

Does not print a value, which makes sense.

Code :

if('a' or 'b' or 'c' in ['notin']):
    print('test')

prints test . Why is 'test' printed as a , b or c is not in notin ?

I'm not implementing this conditional correctly ?

This is not a duplicate question as solution based on reading comments I've written is unique :

if any (t in ['a' , 'b' , 'c'] for t in ['a' , 'b']) :
    print('in list')

if not any (t in ['a' , 'b' , 'c'] for t in ['d' , 'e']) :
    print('not in list')
blue-sky
  • 51,962
  • 152
  • 427
  • 752
  • 4
    In short: `'a' or 'b' or 'c' in ['notin']` is evaluated as `bool('a') or bool('b') or ('c' in ['notin'])` and `bool('a')` is `True`. Use `any` instead. – tobias_k May 28 '18 at 11:34
  • I would put a,b,c in one list and than loop to check if that is available in another list. – Tara Prasad Gurung May 28 '18 at 11:45
  • Also, note that even `'n' in ['notin']` would yield `False`, as it tests membership in the _list_, not in the string _within_ the list. Try `any(c in "notin" for c in ('a', 'b', 'c'))`, i.e. without the `[...]` around the string. – tobias_k May 28 '18 at 11:47
  • @blue-sky Still quite complicated, `any((x in "notin" for x in ("a", "b", "c")))` would do. – guidot May 28 '18 at 13:27

1 Answers1

-1

The reason you get test showing is that the evaluation is seen as

((('c' in 'notin') or 'b') or 'a')
((( FALSE ) or TRUE ) or TRUE )

since

if ('b'):
    print ('test')

evaluates to 'TRUE' and prints 'test' so does your sample. The short answer is yes you implemented your conditional incorrectly.

webmite
  • 575
  • 3
  • 6
  • This does not work (testing if 'o' is in 'notin' yields false). Please don't post answers with untested suggestions ... – meissner_ May 28 '18 at 11:40
  • Correction, actually it just tests `if ('a' in ['notin'])`, as `('a' or 'b' or 'c')` evaluated to just `'a'`. Still wrong. – tobias_k May 28 '18 at 11:45