Python - Parentheses group sub expressions

Introduction

When you enclose sub expressions in parentheses, you override Python's precedence rules.

Python always evaluates expressions in parentheses first before using their results in the enclosing expressions.

For instance, instead of coding X + Y * Z, you could write one of the following to force Python to evaluate the expression in the desired order:

(X + Y) * Z 
X + (Y * Z) 

In the first case, + is applied to X and Y first, because this subexpression is wrapped in parentheses.

In the second case, the * is performed first (just as if there were no parentheses at all).

Adding parentheses in large expressions increases code readability.

Related Topic