Here is a related question that links to docs on evaluation order: Tuple unpacking order changes values assigned
From https://docs.python.org/3/reference/expressions.html#evaluation-order, the example expr3, expr4 = expr1, expr2
shows evaluation order through the suffix number. It shows that the right side of assignment is evaluated first, from left to right, then the left side of assignment is evaluated, also from left to right.
For mutable objects like in this question, it gets more confusing without knowing the evaluation order.
To prove that it is indeed left-to-right on the left-hand-side, you can imagine what happens when pre, node.next, node = node, pre, node.next
is assigned from right-to-left, meaning:
node = node.next
node.next = pre
pre = node
This wouldn't be reversing the Linked List at all.
Other ways to write this reversal:
Sometimes you can see others express this pattern as
pre, pre.next, node = node, pre, node.next
(Notice the 2nd element on LHS changed from node.next
to pre.next
.
This still works because after the first evaluation of pre = node
, pre
and node
are referring to the same node. However, it introduces an extra dependency on the first evaluation of pre = node
, which adds unnecessary cognitive load on the reader.
If we remained at pre, node.next, node = node, pre, node.next
, then even swapping the first two variables (do it on both left and right of assignment) works:
node.next, pre, node = pre, node, node.next
.
This is also my most preferred form since the right-hand-side naturally follows a previous,current,next order of the linked list.
Generally, we should place the dependent objects on the left of independent objects when ordering a tuple of variables on the left-hand-side. Any ordering with node = node.next
before node.next = pre
should break the implementation. (One example already shown in the thought experiment above on right-to-left evaluation order.)