-2

I'd like to understand why the conjunction of results of IN operator in Python it not working as regular conjunction.

Example:

  1. False and False and True = False (obvious)
  2. 'a' in 'ccc' and 'b' in 'ccc' and 'c' in 'ccc' = False (ok)
  3. 'a' and 'b' and 'c' in 'ccc' = True (blows my mind)

I'd expect that the third line would return the same values as the first and second ones, but it's not.

Why is it so?

Maria
  • 9
  • 2

3 Answers3

1

The statement

'a' and 'b' and 'c' in 'ccc' = True

considers 3 conditions:

'a'
'b'
'c' in 'ccc'

Empty strings are seen as False, while non-empty strings (of any length) yield True. So, a yields True and b yields True. For 'c' in 'ccc', you already mentioned in your OP you understand that. Lastly, to sum up

True and True and True == True
Lexpj
  • 921
  • 2
  • 6
  • 15
1

Your Operation results in true as:

result = 'a' and 'b' and 'c' in 'ccc'
#is the same as
result = bool('a') and bool('b') and bool('c' in 'ccc')
#i.e
result = True and True and True #which is true
Bibhav
  • 1,579
  • 1
  • 5
  • 18
0

There are strict rules on Operator precedence, which is how expression is implicitly "parenthesized". in has higher precedence, so it is evaluated first, before any of conjunctions.

Nikolaj Š.
  • 1,457
  • 1
  • 10
  • 17