Table of Contents
What Will You Learn
In this section, you'll explore how Python evaluates expressions by precedence and associativity rules. You’ll learn which operators take priority in mixed expressions, how parentheses override default behavior, and how to avoid common mistakes. Mastering precedence ensures accurate and predictable results in your code.
In any programming language, the order in which operations are performed plays a crucial role in how expressions are evaluated. Python is no exception. This section is dedicated to understanding operator precedence, which determines how expressions with multiple operators are grouped and executed. Without knowing precedence rules, beginners often make logical mistakes that produce unexpected results.
Imagine an expression like 3 + 4 * 5
. Should Python add first or multiply first? The answer depends on operator precedence. While parentheses can override this
behavior, a clear understanding of default operator priority helps avoid confusion and makes your code predictable and clean.
Operator precedence is especially important in complex expressions involving arithmetic, comparison, logical, and bitwise operators. This topic is essential for writing correct conditions, assignments, and function calls. Let’s explore how precedence works and what rules govern Python’s expression evaluation.
What Is Operator Precedence in Python?
Operator precedence in Python defines the sequence in which operations are performed in expressions. When an expression contains multiple types of operators,
Python follows a specific priority order to evaluate them correctly. This ensures that a + b * c
is interpreted as a + (b * c)
, not
(a + b) * c
. The operators with higher precedence are evaluated before the ones with lower precedence.
Each category of operator—arithmetic, comparison, logical, bitwise—has its own precedence level. Understanding these rules avoids logic bugs and makes expressions more predictable.
You can always use parentheses to change the default behavior and make your intentions explicit.
Below is the complete operator precedence table in Python. The higher an operator is in the table, the earlier it is applied in the expression.
Operator Precedence Table (from highest to lowest):
Precedence Level | Operators | Description |
1 | () |
Parentheses (expression grouping) |
2 | ** |
Exponentiation |
3 | +x , -x , ~x |
Unary plus, minus, bitwise NOT |
4 | * , / , // , % |
Multiplication, division, floor division, modulo |
5 | + , - |
Addition, subtraction |
6 | << , >> |
Bitwise shift left, right |
7 | & |
Bitwise AND |
8 | ^ |
Bitwise XOR |
9 | ` | ` |
10 |
== , != , > , < , >= , <= , is , is not , in ,
not in
|
Comparisons |
11 | not |
Logical NOT |
12 | and |
Logical AND |
13 | or |
Logical OR |
14 | if...else |
Conditional expression |
15 | lambda |
Lambda expression |
16 | = , += , -= , *= , etc. |
Assignment operators |
This table is essential when you start writing complex expressions.
Which Operator Has the Highest Precedence in Python?
In Python, the operator with the highest precedence is parentheses ()
, used for grouping expressions. When parentheses are placed around parts of an expression, Python evaluates that part first, regardless of the other operators
involved. This allows developers to override the natural precedence and ensure a specific evaluation order. For example, in (3 + 2) * 4
, the addition is performed
first due to parentheses, not the multiplication. Parentheses enhance readability and prevent logical errors in complex expressions.
Which Operator Has the Lowest Precedence in Python?
The operator with the lowest precedence in Python is the assignment operator (=
, +=
, -=
, etc.). This
means that assignment happens only after all other operations within the expression have been evaluated. For instance, in x = 2 + 3 * 4
, the multiplication and
addition are performed before assigning the final value to x
. This rule ensures that variables are always assigned fully computed values. Understanding this behavior
is essential for writing clear and correct assignment statements.
What Are the Rules for Operator Precedence in Python?
Operator precedence in Python defines the order in which operations are performed in an expression with multiple operators. Without clear precedence rules,
complex expressions could be misinterpreted, leading to unexpected results. Python uses a hierarchy of precedence levels to decide which operations come first. For example,
multiplication and division take precedence over addition and subtraction. However, parentheses can override this order and enforce a custom sequence. When multiple operators
share the same level, Python evaluates them based on associativity, which is usually from left to right, except for exponentiation
(**
), which is right to left.
These precedence rules are fixed by the language and must be followed strictly to avoid logic errors. Knowing these rules helps beginners write more predictable and correct code. Below are key rules that control operator precedence in Python:
-
Parentheses
().
Used to group expressions and enforce custom evaluation order. Operations within parentheses are always executed first. -
Exponentiation
**.
Has higher precedence than most arithmetic operators. Evaluated right to left, meaning2 ** 3 ** 2
is interpreted as2 ** (3 ** 2)
. -
Unary operators
+x
,-x
,~x.
These are evaluated after exponentiation but before multiplication or division. They apply to a single operand. -
Multiplication, Division, Floor Division, Modulus
* / // %.
These operators share the same precedence and are evaluated from left to right. -
Addition and Subtraction
+ -.
These have lower precedence than multiplication and division. Also evaluated left to right. -
Comparison operators
< > <= >= == !=.
These are used to compare values and are evaluated after arithmetic operations. -
Assignment
=
,+=
,-=
and others. These have the lowest precedence, ensuring all computations are completed before the value is assigned.
Mastering these rules ensures your expressions behave as intended and improves overall code clarity.
What Are Some Common Pitfalls When Dealing with Operator Precedence in Python?
Understanding operator precedence is essential to writing correct and predictable Python code. Beginners often run into subtle bugs when they assume operations execute in a different order than they actually do. Below are six common pitfalls and how to resolve them:
1. Misunderstanding arithmetic operator precedence
A classic mistake is assuming addition happens before multiplication. For example:
result = 10 + 5 * 2 # Outputs 20, not 30
This happens because *
has higher precedence than +
.
Fix: Use parentheses to force the desired order:
result = (10 + 5) * 2 # Now outputs 30
2. Forgetting parentheses in logical conditions
A condition like if x > 10 and x < 20 or y == 5:
may not behave as expected. and
has higher precedence than or
, so Python evaluates
it as ((x > 10 and x < 20) or y == 5)
.
Fix: Use parentheses to make logic explicit:
if (x > 10 and x < 20) or (y == 5):
3. Misinterpreting exponentiation and unary minus
Code like -3 ** 2
returns -9
because **
has higher precedence than unary -
. Python interprets it as -(3 ** 2)
.
Fix: Wrap the base in parentheses:
(-3) ** 2 # Returns 9
4. Ignoring precedence in chained comparisons and logic
Example:
if a == b and c == d or e == f:
This is evaluated as ((a == b and c == d) or e == f)
, which might be unintended.
Fix: Always group logical parts clearly:
if (a == b and c == d) or (e == f):
5. Misunderstanding associativity in chained operations
Python’s exponentiation operator **
is right-associative. So 2 ** 3 ** 2
becomes 2 ** (3 ** 2)
which is 2 ** 9 = 512
,
not (2 ** 3) ** 2 = 64
.
Fix: Always add parentheses for clarity:
(2 ** 3) ** 2 # Use this if you want 64
6. Incorrect chaining of assignments
Beginners sometimes try this:
x = y + z = 10 # SyntaxError
This is invalid in Python. Unlike some other languages, chained assignment doesn’t allow this format.
Fix: Split into valid separate steps:
y = z = 10
x = y + z
Summary: Always use parentheses when combining multiple operators or when in doubt. It improves code readability and prevents logic errors due to misunderstood precedence rules.
FAQ
1. In which manner are operators with the same precedence evaluated in Python?
When two or more operators in an expression have the same precedence level, Python uses a rule called associativity to determine the order of evaluation. Most
operators in Python are left-associative, meaning the evaluation proceeds from left to right. For example, in the expression
10 - 5 - 2
, Python calculates (10 - 5) - 2
, not 10 - (5 - 2)
. However, some operators like the
exponentiation operator (**
) are right-associative, meaning Python evaluates them from right to left. So
2 ** 3 ** 2
becomes 2 ** (3 ** 2)
which equals 512
, not (2 ** 3) ** 2
. To avoid confusion, especially in complex
expressions, it's a good practice to use parentheses explicitly. This makes the logic of your code clear both to Python and to other developers (or your future
self).
2. What happens if I don’t consider operator precedence in my expressions?
Neglecting operator precedence can lead to subtle and difficult-to-trace bugs in your code. For example, if you write result = 5 + 3 * 2
, you might expect it to be
(5 + 3) * 2 = 16
, but Python calculates it as 5 + (3 * 2) = 11
because multiplication has higher precedence than addition. Such misunderstandings are
common among beginners and often cause logic errors rather than syntax errors — making them harder to detect. These bugs can break core logic in calculations, conditions,
or loops. To avoid these mistakes, always understand how Python evaluates each part of the expression, or use parentheses to clarify your
intentions explicitly.
3. Why is the exponentiation operator (**
) evaluated from right to left?
The exponentiation operator in Python (**
) is right-associative, which means that in expressions like 2 ** 3 ** 2
, Python evaluates
the rightmost **
first. So it becomes 2 ** (3 ** 2)
→ 2 ** 9
→ 512
. This rule exists to support mathematical
convention for exponentiation. If you want to change this behavior (e.g., force (2 ** 3) ** 2
), you must use parentheses explicitly. Beginners often assume it
behaves like other arithmetic operators (which are left-associative), so this difference can cause confusion or incorrect outputs. Understanding this exception is crucial when
working with nested powers or when chaining multiple exponentiations in formulas.
4. How can I control the order of operations in Python?
To control the order of operations, you should use parentheses. Python evaluates expressions inside parentheses first, regardless of operator precedence. For
example, without parentheses, 5 + 2 * 3
evaluates to 11
, but with parentheses (5 + 2) * 3
, the result is 21
. Using
parentheses not only ensures your logic is followed correctly but also improves readability for others (or your future self). It’s especially useful in complex
conditional statements, mathematical formulas, or combined logical expressions. Never rely solely on precedence rules unless you're absolutely confident in them —
parentheses are the safest and clearest way to manage evaluation order.
5. Are logical operators affected by operator precedence?
Yes, logical operators like and
, or
, and not
are subject to operator precedence in Python. Among them, not
has the
highest precedence, followed by and
, and then or
. This affects how compound conditions are evaluated. For example, in
True or False and False
, Python evaluates the and
part first, resulting in True or (False and False)
→
True or False
→ True
. If you intended for the or
to happen first, the logic would break. That's why it's critical to use
parentheses to group logic properly. Understanding how these operators interact is essential for building correct if
conditions, loops, and
assertions.