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.
Table 5.2. Operator Precedence
Operator | Description |
---|---|
lambda | Lambda Expression |
or | Boolean OR |
and | Boolean AND |
not x | Boolean NOT |
in, not in | Membership tests |
is, is not | Identity tests |
<, <=, >, >=, !=, == | Comparisons |
| | Bitwise OR |
^ | Bitwise XOR |
& | Bitwise AND |
<<, >> | Shifts |
+, - | Addition and Subtraction |
*, /, % | Multiplication, Division and Remainder |
+x, -x | Positive, Negative |
~x | Bitwise NOT |
** | Exponentiation |
x.attribute | Attribute reference |
x[index] | Subscription |
x[index:index] | Slicing |
f(arguments, ...) | Function call |
(expressions, ...) | Binding or tuple display |
[expressions, ...] | List display |
{key:datum, ...} | Dictionary display |
`expressions, ...` | String conversion |
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.
By default, the operator precedence table decides which operators are evaluated before others. However, if you want to change the order in which they are evaluated, you can use parentheses. For example, if you want the addition to be evaluated before multiplication in an expression like 2 + 3 * 4 , then write the expression as (2 + 3) * 4.
Operators are usually associated from left to right i.e. operators with same precedence are evaluated in a left to right manner. For example, 2 + 3 + 4 is evaluated as ((2 + 3) + 4). Some operators like assignment operators have right to left associativity i.e. a = b = c is treated as (a = (b = c)).