Python Operator Precedence and Associativity
The article explains how Python determines the order of evaluation for multiple operators by using precedence rules and associativity, lists the full precedence table, illustrates left‑ and right‑associative operators with examples, and offers best‑practice tips for writing clear expressions.
When several operators appear together in a Python expression, the interpreter first compares their precedence and evaluates them from highest to lowest; operators with the same precedence are then resolved according to their associativity (left‑to‑right or right‑to‑left).
For example, in the arithmetic expression 2 + 4 * 3 , multiplication has higher precedence than addition, so the multiplication is performed first.
Python's operator precedence hierarchy (from highest to lowest) includes:
Parentheses ()
Exponentiation **
Unary plus/minus and bitwise NOT ~
Multiplication, division, floor division, modulo * / // %
Addition and subtraction + -
Bitwise shifts > <<
Bitwise AND &
Bitwise XOR and OR ^ |
Comparison operators < <= > >=
Equality operators == !=
Assignment operators = %= /= //= -= += *= **=
Identity operators is / is not
Membership operators in / not in
Logical operators and / or / not
Associativity determines the order when operators share the same precedence. Most operators are left‑associative, meaning evaluation proceeds from the left; exponentiation ** , unary signs, and assignment operators are right‑associative.
<code>>> 5 / 2 * 4 # left‑associative operators
10.0
>>> 2 ** 2 ** 3 # right‑associative, equivalent to 2 ** (2 ** 3)
256
</code>Although Python follows these rules, writing overly long or complex expressions is discouraged because it harms readability. The article recommends two best practices: keep expressions short or split them into simpler parts, and use parentheses liberally to make evaluation order explicit.
Author: Liu Wenfei
Python Programming Learning Circle
A global community of Chinese Python developers offering technical articles, columns, original video tutorials, and problem sets. Topics include web full‑stack development, web scraping, data analysis, natural language processing, image processing, machine learning, automated testing, DevOps automation, and big data.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.