2

I was answering another question and came across something similar to this:

n = 1
l = [1, 2, 3]

print(n in l is True)
# False

# same for:
print(n in l == True)
# False

When I looked at it, I intuitively knew what was wrong, but after trying to explain the issue I noticed I don't actually understand the problem here.

It might be a silly question, but why does this return False?

Edit: I know the is True is not required and I could solve it by using brackets around n in l

Andreas
  • 8,694
  • 3
  • 14
  • 38
  • 1
    Maybe https://stackoverflow.com/questions/132988/is-there-a-difference-between-and-is –  Aug 27 '21 at 13:26
  • @Sujay was my first idea as well, but `==` will also return False – Andreas Aug 27 '21 at 13:28
  • 4
    Because it's interpreted as `(n in l) and (l == True)` -> `True and False` -> `False`. – jonrsharpe Aug 27 '21 at 13:28
  • but `l` in non-empty list, it should be interpreted as `True`. No? – Prophet Aug 27 '21 at 13:30
  • 1
    [Be careful with chained operations](https://github.com/satwikkansal/wtfPython#-be-careful-with-chained-operations) – Sayse Aug 27 '21 at 13:30
  • @Prophet it's _truthy_, but that's not the same as being equal to `True`. – jonrsharpe Aug 27 '21 at 13:31
  • 1
    What you think happens: `(n in l) is True`. What happens: `(n in l) and (l is True)`. – timgeb Aug 27 '21 at 13:32
  • @jonrsharpe and @timgeb ahh! so its basically a chain of `and` operations between each pair. What confused me was that if you unpack the chain `l` is used twice, once with `n` and once with `is True`. Thank you very much for the explaination. – Andreas Aug 27 '21 at 14:08

0 Answers0