Python Tutorial - Operator Precedence and Associativity

Python Exercise Lists

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.

Operator Description Python Operators Priority Cohesiveness
Parentheses ( ) 19 (Highest) No
Index operator x [i] or x [i1: i2 [: i3]] 18 Left
Attribute access x.attribute 17 Left
Power ** 16 Left
Bitwise negation ~ 15 Right
Symbolic operator +, - 14 Right
Multiply and divide *, /, //, % 13 Left
Addition and subtraction +, - 12 Left
Displacement >>, << 11 Left
Bitwise AND & 10 Right
Bitwise XOR ^ 9 Left
Bitwise OR | 8 Left
Comparison operator ==, !=, >, >=, <, <= 7 Left
is operator is, is not 6 Left
in operator in, not in 5 Left
Logical negation not 4 Right
Logical AND and 3 Left
Logical OR or 2 Left
Comma operator exp1, exp2 1 (Lowest) Left

As a result of the operator precedence in above table, we try to analyse the results of the following expressions:

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 it separately.

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 whenever possible.

Conclusion

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.

                               


More Tutorials:

Python Installation - Linux (Ubuntu)
Python Installation - Mac OS
Integrated Development Environment - IDE
Python - Basic Variables
Python - Sequence Introduction
Python - Output Formatting
Python - Escape Character
Python - Type Conversion
Python - Numbers
Python – Arithmetic Operators
Python – Assignment Operators
Python – Comparison Operators
Python – Logical Operators
Python – Precedence and Associativity Operators
Python – Bytes Type and Usage
Python – Long & Raw Strings
Python – Concatenate Function
Python – Slice Function
Python – Length and Split Function
Python – Join and Count Function
Python – Find Function
Python – Index Function
Python – Alignment Function
Python – Startswith and Endswith Function
Python – String Case Conversion
Python – Remove Specified Character
Python – Encode and Decode Function
Python – dir and help Function
Python – Input Output Introduction
Python – Basic Operation
Python – Open Function
Python – Read Function
Python – Readline Function
Python – Write Function
Python – Close Function
Python – Seek and Tell Function
Python – Pickle Module
Python - File Input Module and Linecache Module
Python - Pathlib Module
Python - Pathlib Module
Python - os.path Module
Python - fnmatch Module
Python - Tuple Introduction
Python - List Introduction
Python - List Add Element
Python - List Delete Element
Python - List Modification Element
Python - List Find Element
Python - Dictionary Introduction
Python - Dictionary Basic Operation
Python - Dictionary Method Guide
Python - Set Collection
Python - Set Basic Operation
Python - Set Basic Method
Python - Frozenset Method
Python - If Condition I
Python - If Condition II
Python - While loop
Python - For loop
Python - Pass Statement
Python - Break Statement
Python - Zip Reverse Function
Python - Function Introduction
Python - Positional Parameters
Python - Key Arguments
Python - None and Return
Python - Variable Scope
Python - Local Function
Python - Closure Method
Python - Lamdba Expression


More Python Exercises:

Python String Exercises
Python List Exercises
Python Library Exercises
Python Sets Exercises
Python Array Exercises
Python Condition Statement Exercises