Why is '(x in list_1) == True' is True but 'x in list_1 == True' is False?

78 Views Asked by At

I know this is can be a very basic question, but I found something curious on Python. I will try to explain this with the following example:

l = [1,2,3,4,5]
n1 = 1

We know the following:

print( n1 in l ) # True # is n1 in the list l1?
print( not(n1 in l) ) # False # is n1 not in the list l1?

instead of not I can use:

print( (n1 in l) == True ) # True 
# this will be like
# True == True
# True  

My question is when I don't use the parentheses, ex:

print( n1 in l == True ) # False

Here the answer from the console is False

I was trying to understand the logic about this

So if I try to do it step by step

n1 in l == True
l == True # this is False, l es not a boolean True, it is a list
n1 in False # this is not False, actually if you run it it will be an error

print( n1 in False) # TypeError: argument of type 'bool' is not iterable

Therefore, why if I run:

print( n1 in l == True )

The answer on the console is False?

Thanks a lot in advance.

print( n1 in l == True ) # True

to be the same as:

print( (n1 in l) == True ) # True 
1

There are 1 best solutions below

0
SpicyCatGames On

It looks like == and in has the same precedence so recommended to use the parentheses.

Doesn't make any sense because in should only work for the types mentioned in the docs but this is the fun of dynamically typed languages :D

https://docs.python.org/3/reference/expressions.html#operator-precedence