Precedence of "in" in Python Precedence of "in" in Python python python

Precedence of "in" in Python


In the context of a for statement, the in is just part of the grammar that makes up that compound statement, and so it is distinct from the operator in. The Python grammar specification defines a for statement like this:

for_stmt ::=  "for" target_list "in" expression_list ":" suite              ["else" ":" suite]

The point to make is that this particular in will not be interpreted as part of target_list, because a comparison operation (e.g. x in [x]) is not a valid target. Referring to the grammar specification again, target_list and target are defined as follows:

target_list     ::=  target ("," target)* [","]target          ::=  identifier                     | "(" target_list ")"                     | "[" target_list "]"                     | attributeref                     | subscription                     | slicing                     | "*" target

So the grammar ensures that the parser sees the first in token after a target_list as part of the for ... in ... statement, and not as a binary operator. This is why trying to write things very strange like for (x in [x]) in range(5): will raise a syntax error: Python's grammar does not permit comparisons like (x in [x]) to be targets.

Therefore for a statement such as for n in "seq1" and "something" is unambiguous. The target_list part is the identifier n and the expression_list part is the iterable that "seq1" and "something" evaluates to. As the linked documentation goes on to say, each item from the iterable is assigned to target_list in turn.


The word in in a for loop is part of a statement. Statements have no precedence.

in the operator, on the other hand, is always going to be part of an expression. Precedence governs the relative priority between operators in expressions.

In statements then, look for the expression parts in their documented grammar. For the for statement, the grammar is:

for_stmt ::=  "for" target_list "in" expression_list ":" suite              ["else" ":" suite]

The and operator in your example is part of the expression_list part, but the "in" part is not part of the expression.

The 'order' then is set in Python's grammar rules, which govern the parser. Statements are the top-level constructs, see the Top-level components documentation (with stand-alone expressions being called expression statements). Expressions are always part of a statement, giving statements priority over anything contained in a statement.