Python Tutorial - Operator Precedence and Associativity
Priority and associativity are two of the important concepts in Python expressions. They determine
which part of the expression is executed first.
Python - Operator Precedence
The so-called priority is which operator is executed first when multiple operators appear in an
expression at the same time.
For example, for the expression a + b * c, Python will first calculate the multiplication and then
the addition; b * c will result in 8 and a + 8 will result in 24, so the final value of d will
also be 24. Calculate * before calculating +, indicating that * has higher priority than +.
Python supports dozens of operators and is divided into nearly twenty priorities. Some operators
have different priorities, and some operators have the same priority. See the table below.
x [i] or x [i1: i2 [: i3]]
Multiply and divide
*, /, //, %
Addition and subtraction
==, !=, >, >=, <, <=
is, is not
in, not in
As a result of the operator precedence in above table, we try to analyse the results of the following
4 + 4 << 2
The priority of + is 12, the priority of << is 11, the priority of + is higher than <<, so execute 4 + 4
first to get the result 8 and then execute 8 << 2 to get the result 32, which is also the final result.
For the case that is not easy to determine the priority, we can add () to the subexpression, which is
written as follows:
(4 + 4) << 2
This seems obvious and is not easy to cause misunderstanding.
Of course, we can also use () to change the execution order of the program, such as:
4 + (4 << 2)
Then execute 4 << 2 to get the result of 16 and then execute 4 + 16 to get the result 20.
Although there is a precedence relationship for Python operators, but it is not recommended to rely too much
on the precedence of the operators, which will make the program less readable. Therefore, it is better
don't write an expression too complicated. If an expression is too complicated, you can try to write
Don't rely too much on the precedence of the operators to control the execution order of the expressions,
so readability is too poor, you should use () to control the execution order of the expressions
When multiple operators appear in an expression, Python will compare the precedence of each operator,
and executes them from high to low order. When operators with the same precedence are encountered,
then according to the cohesiveness degree to decide which operator to execute first: If it is left
cohesiveness, the left operator is executed first, and if it is right cohesiveness, the right operator
is executed first.