Reputation: 564
I was going over an assignment, and came across something that confused me, as am I not crazy good with python. Here is the code.
def main():
list = [1,2]
x = 2
if (x in list == True):
print("hi")
if (x in list):
print("Why does this proc?")
main()
I believed the output would be both, but the output is only the second if statement. I know that in C, if you had something like
if (x = 6)
That since there is only one '=' that x is now equal to 6. (As its read, if (), x = 6).
Is something similar happening to this python code? Is it checking 'list == true' first, then from there checking about x being in list?
Any insight would be greatly appreciated!
Upvotes: 1
Views: 413
Reputation: 49318
As you can see, yes, your expression requires explicit grouping:
>>> 2 in [1,2] == True
False
>>> (2 in [1,2]) == True
True
Note that, as @tavo and @MorganThrapp mention, the version without parentheses is doing a chained comparison, checking that 2 in [1,2]
and then checking that [1,2] == True
. The latter is false, so the full expression is also false.
By the way, don't name your variables after built-ins like list
, or you won't be able to use those functions easily.
Also, you don't have to compare the result of an expression to True
:
>>> 2 in [1,2]
True
Doing so is the equivalent of asking "is 'the cake is ready' a true statement?" as opposed to "is the cake ready?".
Upvotes: 6