In the previous article we were talking about operator associativity. Also, in one of my previous articles we were talking about the precedence of operators. In this article we’ll be talking about nonassociative operators.
Here’s the video version of this article:
Some operators that are on the same level of precedence are nonassociative. The assignment and comparison operators belong in this group.
Assignment Operators
Let’s have a look at the assignment operators first. The basic assignment operator works in such a way that the last value is assigned to all the variables on the way:
>>> a = 5
>>> b = 3
>>> c = 4
>>> a = b = c
>>> a
4
>>> b
4
>>> c
4
If we try to do something similar with an augmented assignment operator, we’ll get an error:
>>> a, b, c = 5, 3, 4
>>> a = b += c
File "<stdin>", line 1
a = b += c
^
SyntaxError: invalid syntax
Comparison Operators
Now let’s have a look at the comparison operators. We can chain comparison operators like in math. So we can write:
>>> 2 < 4 < 7
True
instead of its equivalent:
>>> 2 < 4 and 4 < 7
True
It works the same for the greater than operator:
>>> 8 > 6 > 3
True
which is an equivalent of this:
>>> 8 > 6 and 6 > 3
True
We can combine the operators in quite interesting ways. They’re just a shorthand for the full form with the logical and operator. So instead of writing 6 < 8 and 8 == 8, we can write:
>>> 6 < 8 == 8
True
Here’s a more complex example:
>>> 3 == 3 < 6 < 8 == 8 < 10
True
But we can also use other combinations, which are not considered correct in math:
>>> 2 < 4 > 3 # same as 2 < 4 and 4 > 3
True
>>> 2 > 1 < 5 # same as 2 > 1 and 1 < 5
True