5
print('a' in 'aa')
print('a' in 'aa' == True)
print(('a' in 'aa') == True)
print('a' in ('aa' == True))

The output is

True
False
True
Traceback (most recent call last):
  File "main.py", line 6, in <module>
    print('a' in ('aa' == True))
TypeError: argument of type 'bool' is not iterable

If line 2 is neither line 3 nor line 4, then what is it? How does it get False?

pete
  • 1,878
  • 2
  • 23
  • 43
  • @PatrickArtner I'm finding it unusually difficult to find the canonical I'm thinking of. It's due to chaining but I can't find the link :/ – roganjosh Nov 21 '18 at 18:23
  • That's the one you originally flagged with but I'm _sure_ there is a canonical. Where is it?! :P – roganjosh Nov 21 '18 at 18:25
  • @roganjosh this here? https://stackoverflow.com/questions/6074018/why-does-the-expression-0-0-0-return-false-in-python/6074117#6074117 – Patrick Artner Nov 21 '18 at 18:27
  • @PatrickArtner Not me! I wondered where it went. I was searching for the main one to add to the dupe. EDIT: maybe I'm thinking of some happy mashup of the two into a single question/answer – roganjosh Nov 21 '18 at 18:28
  • It is similar to 'a < b < c'. – VPfB Nov 21 '18 at 18:34
  • 1
    @PatrickArtner it got hammered and they presumably decided to reverse that, but now it shows no close votes to me. – roganjosh Nov 21 '18 at 18:42
  • 1
    @PatrickArtner i saw timgeb as the second closer. It must be a hammer. I'm not sure how to view that history, though. – roganjosh Nov 21 '18 at 18:46
  • I hammered and then decided that hammer may have been premature. – timgeb Nov 21 '18 at 19:18

2 Answers2

9

According to Expressions

print('a' in 'aa' == True)

is evaluated as

'a' in 'aa' and 'aa' == True

which is False.

See

print("a" in "aa" and "aa" == True)

==> False

The rest is trivial - it helps to keep operator precedence in mind to figure them out.


Similar ones:

with different statements. I flagged for dupe but the UI is wonky - I answered non the less to explain why yours exactly printed what it did.

Patrick Artner
  • 50,409
  • 9
  • 43
  • 69
1

Case 1 : it's simple the answers is True.

print('a' in 'aa')

Case 2 : This operation is evaluated as 'a' in 'aa' and 'aa' == True, so obviously it will return false.

print('a' in 'aa' == True)

Case 3: Now because we have () enclosing ('a' in 'aa') and the precedence of () is highest among all so first 'a' in 'aa' is evaluated as True and then True == True

print(('a' in 'aa') == True)

Case 4 : Same as above because of precedence of (), its evaluated as 'aa' == True, which will result in error as it tries to apply in on a non iterable that is bool value.

print('a' in ('aa' == True))
Sanchit Kumar
  • 1,545
  • 1
  • 11
  • 19