Operator Precedence and Associativity
We'll cover the following
- Operator precedence
- Parentheses ()
- Exponentiation **
- Unary operators +x, -x, ~x
- Multiplication *, division /, floor division //, modulus %
- Addition + and subtraction -
- Bitwise shift operators <<, >>
- Bitwise AND &
- Bitwise XOR ^
- Bitwise OR |
- Comparison and membership operators in, not in, is, is not, <, <=, >, >=, !=, ==
- Logical NOT not
- Logical AND and
- Logical OR or
- Associativity
Operator precedence
Operators are called in a specific order when they’re used in an expression. Simply put, operator precedence determines the order in which the operations are performed. The order below details the operator precedence that Python follows.
Parentheses ()
Used to group expressions and alter the default order of operations.
Exponentiation **
Raises the left operand to the power of the right operand.
Unary operators +x
, -x
, ~x
Performs unary plus, unary minus, and bitwise NOT.
Multiplication *
, division /
, floor division //
, modulus %
Performs multiplication, division, floor division, and modulus operations.
Addition +
and subtraction -
Adds or subtracts two operands.
Bitwise shift operators <<
, >>
Performs left and right bitwise shifts.
Bitwise AND &
Performs bitwise AND operation.
Bitwise XOR ^
Performs bitwise exclusive OR operation.
Bitwise OR |
Performs bitwise OR operation.
Comparison and membership operators in
, not in
, is
, is not
, <
, <=
, >
, >=
, !=
, ==
Checks for membership (i.e., if it’s included in a sequence and identity or is an object and performs comparisons).
Logical NOT not
Returns True
if the operand is False
and vice versa.
Logical AND and
Returns True
if both operands are True
.
Logical OR or
Returns True
if one of the operands is True
.
Associativity
When two or more operators share the same precedence, associativity comes into play. Associativity dictates the order in which the expression is evaluated, whether from left to right or right to left. Almost all operators follow left-to-right associativity, meaning the expression is evaluated from the beginning in order. However, a few operators—such as exponentiation, unary positive, unary negative, bitwise NOT, and boolean NOT—exhibit right-to-left associativity.
Let’s take a mathematical example and break down it’s precedence:
mathematical_expression = 2 + 3 * 5 ** 2 - 10 // 2 + (1 - 1)print(mathematical_expression)
2 + 3 * 5 ** 2 - 10 // 2 + (1 - 1)
2 + 3 * 5 ** 2 - 10 // 2 + 0
2 + 3 * 25 - 10 // 2 + 0
2 + 75 - 10 // 2 + 0
2 + 75 - 5 + 0
77 - 5 + 0
72 + 0
72
We start with the parenthesis expression, followed by exponentiation. We then have two operators with similar precedence (i.e. multiplication and division), so we perform it from left to right. Similarly, we perform addition and subtraction from left to right, as these operators also have the same level of precedence. The final answer we get is 72.