3
>>> g = [2, True, 5]
>>> print(2 in g in g)
False

>>> g.append(g)
>>> print(2 in g in g)
True

Why is the first snippet outputting False when there is 2 and 'True' both in the list?

Why is it outputting True after appending 'g' ?

  • Related question: https://stackoverflow.com/questions/25753474/python-comparison-operators-chaining-grouping-left-to-right – mkrieger1 Oct 25 '20 at 20:06

2 Answers2

8

This is operator chaining and will expand to 1 in g and g in g. So only after you append g to itself this becomes true.

You can use parentheses to get the behavior you want: (1 in g) in g. This forces the 1 in g part to be evaluated first (however in compares for equality and True == 1 so True doesn't need to be part of the list actually).

a_guest
  • 34,165
  • 12
  • 64
  • 118
0

It works on the principle of operator chaining So print(1 in g in g) is equivalent to print(1 in g and g in g) resulting in

False (True and False)