>A Byte of Python

Operator Precedence

If you had an expression such as 2 + 3 * 4, is the addition done first or the multiplication? Our high school maths tells us that the multiplication should be done first. It means that the multiplication operator has higher precedence that the addition operator.

The following table gives the operator precedence table for Python, from the lowest precedence (least binding) to the highest precedence (most binding). This means that in an expression, Python will first evaluate the operators lower in the following table before the operators listed higher in the table.

I have given the following list for the sake of completeness. I strongly advise you to use parentheses for grouping of operators and operands in order to explicitly specify the precedence and to make the program as readable as possible. For example, 2 + (3 * 4) is definitely easier to understand than 2 + 3 * 4. As with everything else, the parentheses should be used sensibly.

The operators which are not already explained will be seen in later chapters.

Operators with the same precedence are listed in the same row in the above table. For example, + and - have the same precedence.