Introduction to Python Programming Cycle of Python Varibles and Datatypes in Python Input and Output in Python Operators in Python Precedence of Operators in Python Typecasting in Python If Else in Python Loops in Python Break, Continue and Pass in Python Functions in Python Default Arguments and Keyword Arguments in Python Strings in python Lists in Python Tuple in Python Dictionary in Python Sets in Python List Comprehension in Python Unpacking Sequences in Python Higher Order Functions in Python Lambda Functions in Python Sieve of Eratosthenes Algorithm in Python Linear Search in Python Binary Search in Python Selection Sort in Python Bubble Sort in Python Insertion Sort in Python Merge Sort in Python

Precedence of Operators in Python

When multiple operators are used in one expression such as +,-, **, or ^, etc, we need to decide the order in which to evaluate different operators on the basis of priority in order to get the correct results.

Python Operator Precedence Table

Precedence Operator Description Associativity
Highest ( ) Parentheses (grouping) Not Applicable
[ ] List indexing Not Applicable
f"[...]" String formatting (f-strings) Not Applicable
... ** ... Exponentiation Right to left
+x, -x Unary plus, Unary minus Not Applicable
~x Bitwise NOT Not Applicable
Higher *, /, % Multiplication, Division, Modulus Left to right
// Floor division (integer division) Left to right
+, - Addition, Subtraction Left to right
<<, >> Bitwise shift operators Left to right
& Bitwise AND Left to right
^ Bitwise XOR Left to right
| Bitwise OR Left to right
<, <=, >, >= Comparison operators Left to right
==, != Equality operators Left to right
not x Boolean NOT Not Applicable
and Boolean AND Left to right
or Boolean OR Left to right
Lowest =, +=, -=, ... Assignment operators Right to left

Example


# Operator precedence example

x = 10 + 5 * 2  # Multiplication has higher precedence than addition
print(x)  # Output: 20

y = (10 + 5) * 2  # Parentheses enforce higher precedence for addition
print(y)  # Output: 30

z = 10 - 5 / 2  # Division has higher precedence than subtraction
print(z)  # Output: 7.5

w = 10 - (5 / 2)  # Parentheses enforce higher precedence for division
print(w)  # Output: 7.5

a = 2 ** 3 ** 2  # Exponentiation right-to-left associativity
print(a)  # Output: 512

b = (2 ** 3) ** 2  # Parentheses enforce higher precedence for exponentiation
print(b)  # Output: 64

Output

20
30
7.5
7.5
512
64