1

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!

TheRealM
  • 27
  • 3
  • 1
    Here’s a question which, I suspect, has the same issue at the bottom: https://stackoverflow.com/questions/9284350/why-does-1-in-1-0-true-evaluate-to-false/9284410#9284410 . – Ture Pålsson Feb 01 '23 at 11:40

1 Answers1

0

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.

TheRealM
  • 27
  • 3