pythonpython-3.xoperatorsmembership

In which order are two or more consecutive membership operators treated in Python?


>>> 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' ?


Solution

  • 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).