0

The below code is for revsesing a linked list given the head of the list

class Solution:
        def reverseList(self, head: ListNode) -> ListNode:

            if head is None or head.next is None:
                return head

            prev = None
            curr = head

            while curr:
                curr.next, prev, curr = prev, curr, curr.next

            return prev

How are we able to assign curr = curr.next(third assignment), when curr.next was assigned prev in the beginning?

Usually, a temp variable is used to store the value of curr.next, how are we bypassing that here?

  • tl;dr "the right-hand side is evaluated before the left-hand side" – wjandrea Jun 13 '20 at 02:15
  • Please explain, does that mean curr = curr.next will happen first? The problem still persists right? –  Jun 13 '20 at 02:33
  • No, the assignments themselves are evaluated from left to right. What I mean is that the names on the left are "resolved" to objects before any assignment takes place. Say for example the loop is in the middle of a long list. The right hand side is going to be evaluated: `prev, curr, curr.next` -> `, , `, then the assignment happens like this: `curr.next = ; prev = ; curr = ` – wjandrea Jun 13 '20 at 02:45
  • 1
    `how are we bypassing that here?` - when the interpreter evaluates `curr.next` on the right-hand-side the result is an object. The interpreter stores that object for use *later* when it assigns it to `curr.next`. So although the main reason is due to [evaluation order](https://docs.python.org/3/reference/expressions.html#evaluation-order). Another part of the reason is that names just *point to* objects, they are not The objects - [Facts and myths about Python names and values](https://nedbatchelder.com/text/names.html). – wwii Jun 13 '20 at 03:00
  • I added [an answer on one of the duplicate questions](https://stackoverflow.com/a/62355029/4518341) to really drive home the point – wjandrea Jun 13 '20 at 03:03

0 Answers0