1
class ListNode:
    def __init__(self,val,next=None) -> None:
        self.val=val
        self.next=next

n3=ListNode(3,n4)
n2=ListNode(2,n3)
n1=ListNode(1,n2)

n2,n2.next,n1=n2.next,n1,n2

if it happen at once, n2.next should be n1, but result shows n2.next=n3. Does it mean n2.next=n1 is executed after n2=n2.next is applied? what did i get wrong?

Silence
  • 11
  • 1
  • 1
    To clarify, by "occur at once" to you literally mean occur in the same exact instance of time? Computationally speaking, this not possible. Each assignment executes in-turn. – S3DEV Jul 29 '21 at 08:57
  • thank you. if i swap order to n2.next, n2, n1 = n1, n2.next, n2 it provides wanted result. i'm confused how order makes difference – Silence Jul 29 '21 at 09:15
  • Are you asking whether/how Python orders assignment *in general*, or are you asking why *your specific code* is order dependent? – MisterMiyagi Jul 29 '21 at 09:19

2 Answers2

2

In python assignment statements, the right side is always evaluated before the values are assigned to the Left side. The result of each variable on your Right hand side i.e. n2.next,n1,n2 is evaluated such that n2.next is 3, n1 is 1 and n2 is 2. The assignment then happens from left to right.

n2.next is first assigned n2, n1 is then assigned to n2.next and n2 is then assigned to n1. So you are right, it proceeds in an order and it is not simultaneous.

Dharman
  • 30,962
  • 25
  • 85
  • 135
Tasbiha
  • 106
  • 5
0

Python evaluates expressions from left to right. Notice that while evaluating an assignment, the right-hand side is evaluated before the left-hand side. Docs

The Assignment happens as follows:

Initial values:

n3 = ListNode(3,n4)
n2 = ListNode(2,n3)
n1 = ListNode(1,n2)
n2, n2.next, n1 = n2.next, n1, n2

Righthand side Evaluation:

 A. n2.next = n3 = (3, n4)
 B. n1 = (1, n2)
 C. n2 = (2, n3)

Assignment from left to right

 1. Now n2 is n2.next which is n3. So n2 = (3, n4) {From A}
 2. n2.next is n1 i.e, n2.next = n1. So n2 = (3, n1) {From B}
 3. n1 is n2. So n1 = (2, n3) {From C}

So Final values are:

n1 = (2, n3)
n2 = (3, n1)
Ram
  • 4,724
  • 2
  • 14
  • 22