Explaining the Output of Comparison Expressions Involving Strings and Lists in Python

40 Views Asked by At

Hej,

I have the following code snippet and I don't understand the output:

a = "foo"
b = "foo"
c = "bar"
foo_list = ["foo", "bar"]


print(a == b in foo_list) # True
print(a == c in foo_list) # False

---
Output: 
True
False

The first output is True. I dont understand it because either a == b is executed first which results in True and then the in operation should return False as True is not in foo_list. The other way around, if b in foo_list is executed first, it will return True but then a == True should return False.

I tried setting brackets around either of the two operations, but both times I get False as output:

print((a == b) in foo_list) # False
print(a == (b in foo_list)) # False
---
Output: 
False
False

Can somebody help me out?

Cheers!

1

There are 1 best solutions below

0
TheRealM On

Ah, thanks @Ture Pålsson.

The answer is chaining comparisons. a == b in foo_listis equivalent to a == b and b in foo_list where a==b is True and b in foo_list is True. If you set brackets, there will be no chaining.