By mistake I have used more than one in keyword in an expression, but the code still works.

What is the meaning of:

"a" in "bar" in "foo"   # in ... ?

naively I thought that this was equivalent to ("a" in "bar") in "foo" or "a" in ("bar" in "foo") but it is not the case since both are not valid. I get the same behaviour in python2 or 3.

in is considered a comparison operator, and from Python’s documentation for them:

Comparisons can be chained arbitrarily, e.g., x < y <= z is equivalent to x < y and y <= z, except that y is evaluated only once (but in both cases z is not evaluated at all when x < y is found to be false).

Formally, if a, b, c, …, y, z are expressions and op1, op2, …, opN are comparison operators, then a op1 b op2 c ... y opN z is equivalent to a op1 b and b op2 c and ... y opN z, except that each expression is evaluated at most once.

Python evaluates from left to right (you can control the flow / grouping with brackets, tho), and comparison operators can be chained arbitrarily so an expression:

"a" in "bar" in "foo" in "baz"

Essentially ends up as:

"a" in "bar" and "bar" in "foo" and "foo" in "baz"

Which resolves to False.

This seems to mean the following:

("a" in "bar") and ("bar" in "foo") – or False

The following might help:

  • "a" in "bar" in "foo" => False
  • "a" in "bar" in "foobar" => True
  • "b" in "bar" in "foobar" => True
  • "c" in "bar" in "foobar" => False

I thought at first that it might have been "a" in ("bar" in "foo"), but that obviously would return the following:

TypeError: argument of type 'bool' is not iterable

Because ("bar" in "foo") returns False

Edit Fixed obvious typos