A Byte of Python

Operator Precedence

In the expression 2 + 3 * 4, is the addition or multiplication carried out first? Our high school maths tells us that multiplication should be done first before the addition. This means that multiplication has higher precedence than addition.

Similarly, Python has a precedence for all of its operators. The following table gives the operator precedence table for Python from the lowest precedence to the highest precedence. This means, that in a given expression, Python will first evaluate the operators lower in the table before the operators listed higher in the table.

The following table is the same as the one in the Python reference manual and is provided for the sake of completeness. I recommend that you glance through this table and refer to it only when required. If you want to avoid ambiguity in your own mathematical expressions, you should use parentheses. For example, 2 + (3 * 4) is more clearer than 2 + 3 * 4.

Table 5.2. 

OperatorDescription
lambdalambda expression
orBoolean OR
andBoolean AND
not xBoolean NOT
in, not inmembership tests
is, is notidentity tests
<, <=, >, >=, !=, ==comparisons
|bitwise OR
^bitwise XOR
&bitwise AND
<<, >>shifts
+, -addition, subtraction
*, /, %multiplication, division, remainder
+x, -xpositive, negative
~xbitwise NOT
**exponentiation
x.attributeattribute reference
x[index]subscription
x[start:end]slicing
f(arguments...)function call
(expressions, ...)binding or tuple display
[expressions, ...]list display
{key:datum, ...}dictionary display
`expressions, ...`string conversion

That seems like an awful lot of operators, but don't worry, they're very easy to use once you understand them. We've already come across some of these operators, we'll learn the others in later chapters.

Note that operators with the same precedence are listed in the same row in the above table. For example, + and - have the same precedence.

Order of evaluation

By default, the operator precedence table decides which operators are evaluated before others. If you want to change the order of evaluation, then use parentheses. For example, in the expression 2 + 3 * 4, if you want the addition to be evaluated before the multiplication, then write the expression as (2 + 3) * 4.

Associativity

Operators are usually associated from left to right i.e. operators with the same precedence are evaluated in a left to right manner. For example, 2 + 3 - 4 is evaluated as (2 + 3) - 4. Some operators like assignment operators have right to left associativity i.e. a = b = c is treated as a = (b = c).