1

So I stumbled upon a problem (solved it eventually via experimentation) with checking for the existence of strings inside a tuple.

if 'String1' or 'String2' in tuple:

evaluated True even if neither were in tuple.

if 'String1' in tuple or 'String2' in tuple:

gives me the desired result.

What did the first variant actually evaluate?

Edit: @Cricket_007 ... the question you pointed to in your dupe report didn't cover the in, therefore I believe this not to be a dupe.

tink
  • 14,342
  • 4
  • 46
  • 50
  • 1
    `if ('String1') or ('String2' in tuple):` – Christian Dean Sep 16 '17 at 00:19
  • Go read the Python operator precedence table. – Barmar Sep 16 '17 at 00:21
  • https://docs.python.org/3/reference/expressions.html#operator-precedence – Barmar Sep 16 '17 at 00:22
  • Thanks @Barmar ... that kind of makes sense, not that I understand what `or`ing two stings does. – tink Sep 16 '17 at 00:23
  • @Serjik Oring anything returns `True` if both are truthy, otherwise `False`. Non-empty strings are truthy, so `('String1' or 'String2')` is `True`. So what you write is `if True in tuple:` – Barmar Sep 16 '17 at 00:25
  • 1
    Possible duplicate of [How do I test one variable against multiple values?](https://stackoverflow.com/questions/15112125/how-do-i-test-one-variable-against-multiple-values) – OneCricketeer Sep 16 '17 at 00:25
  • 2
    Consider using any as in `any(s in tuple for s in ('String1', 'String2'))`. Your issue is `'String1'` is 'truthy' as you have written it So `if True or 'String2' in tuple` will be `True` and is equivalent. – dawg Sep 16 '17 at 00:31
  • You were testing `'String1'` or `'String2' in tuple`. `if 'String1'` is always `True` if not `''`. – pylang Sep 16 '17 at 00:49

1 Answers1

3

The difference is the in container checking, If you break this statement: if 'String1' or 'String2' in tuple:

  • 'String1' returns True because testing str() returns True as long as the string is not empty

  • 'String2' in tuple returns True only if the string is contained in the tuple

The first condition always returns True.

The second line tests both variables for in containment first, and then performing or between the results

Chen A.
  • 10,140
  • 3
  • 42
  • 61
  • Thanks for the response, @Vinny, so because 'True' or (string2 in tuple) [which happens to be false] the whole thing is True? – tink Sep 16 '17 at 00:37
  • 1
    @tink that's right. python breaks down the tests to `String1` OR `String2 in tuple`. The first always returns True – Chen A. Sep 16 '17 at 00:43