Skip to content
Home » Operator Associativity in Python

Operator Associativity in Python

Spread the love

In one of my previous articles we were talking about the precedence of operators.

Today we’ll be talking about operator associativity. This is about the order of evaluation of operators.

Here’s the video version of this article:

Some operators share the same level of precedence with other operators, like for example multiplication and modulus. Such operators are evaluated from left to right. One exception is the exponent operator, which is evaluated in the opposite direction. The order in which operators are evaluated in an expression is called operator associativity. So, in most cases we have left-to-right associativity and in the case of the exponent operator we have right-to-left associativity.

Here are some examples:

Here the order is from left to right:

 >>> 3 * 4 % 5          # 12 % 5 = 2
 2 

We can change the order by using parentheses:

 >>> 3 * (4 % 5)        # 3 * 4 = 12
 12 

Again from left to right:

 >>> 3 % 4 * 5          # 3 * 5 = 15
 15 

Your Panda3D Magazine

Make Awesome Games and Other 3D Apps

with Panda3D and Blender using Python.

Cool stuff, easy to follow articles.

Get the magazine here (PDF).

And again we can use parentheses to change the order:

 >>> 3 % (4 * 5)        # 3 % 20 = 3
 3 

And now the exponent operator. This one is evaluated from right to left:

 >>> 2 ** 3 ** 2        # 2 ** 9 = 512
 512

If you need a different order, the parentheses are a solution:

>>> (2 ** 3) ** 2      # 8 ** 2 = 64
64

Python Jumpstart Course

Learn the basics of Python, including OOP.

with lots of exercises, easy to follow

The course is available on Udemy.

Blender Jumpstart Course

Learn the basics of 3D modeling in Blender.

step-by-step, easy to follow, visually rich

The course is available on Udemy and on Skillshare.


Spread the love
Tags:

Leave a Reply