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 - this means that the multiplication operator has higher precedence than 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 a given expression, Python will first evaluate the operators lower in the table before the operators listed higher in the table.
The following table (same as the one in the Python reference manual) is provided for the
sake of completeness. However, I 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 more clearer
than 2 + 3 * 4
. As with everything else, the parentheses shold be used
sensibly and should not be redundant (as in 2 + (3 + 4)
).
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 we have not already come across will be explained in later chapters.
Operators with the same 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 orer in which they are
evaluated, you can use parentheses. For example, if you want addition to be
evaluated before multiplication in an expression, then you can write something
like (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)
.