DEV Community

Charlton Asino
Charlton Asino

Posted on

Python Evaluates Assignments From Right To Left

Why does it matter?
Assigning variables in Python may range from simple statements such as count=5 to others that may require evaluation such as str_len=len("eat one piece of the fruit and you drown")

When assigning variables in Python the evaluation
is done from right to left.Meaning the length of the string str_len will be evaluated first and then assigned.

Tuples are immutable
When working with more complex objects the evaluation order may affect the behaviour of your objects.An example being tuples.Tuples are immutable in Python in that they cannot be modified once created.

>>> a=(1, [2,3,4])
>>> type(a)
<class 'tuple'>
>>> a[0]=8
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'tuple' object does not support item assignment
>>> a[1]=[5,6,7,8]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'tuple' object does not support item assignment
>>> a
(1, [2, 3, 4])
Enter fullscreen mode Exit fullscreen mode

Modifying tuple a raises an exception and inspecting it after shows that the tuple has not been modified.
Murky waters
Depending on how a tuple is operated on and its composition, you can get some unexpected behaviour(they become mutable). This can occur when using augmented assignment operators in particular __iadd__ (in-place addition) which is commonly used as +=.

>>> a
(1, [2, 3, 4])
>>> a[1]+=[100,101,700]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'tuple' object does not support item assignment
Enter fullscreen mode Exit fullscreen mode

An attempt to modify the tuple raises an exception which conforms to the expected behaviour that tuples are immutable.

>>> a
(1, [2, 3, 4])
>>> a[1]+=[100,101,700]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'tuple' object does not support item assignment
>>> a
(1, [2, 3, 4, 100, 101, 700])
Enter fullscreen mode Exit fullscreen mode

But on inspection as per the above example.The tuple has been modified ,the list in the tuple in particular even though we got an exception.

This occurred due to two aspects of the code:

  • In-place addition which is supported in lists.

  • Evaluation of assignments from right to left.

a[1] is a list [2, 3, 4] which supports inplace addition .The statement a[1]+=[100,101,700] is evaluated from right to left meaning the list at a[1] is modified first then a assigned into the tuple and this raises an exception.

Take away
Understading how python evaluates statements is important, especially when performing operations on objects which contain types with different behaviours.

Top comments (0)