Silence
Silence

Reputation: 11

python multiple assignment doesn't seem to occur at once

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?

Upvotes: 1

Views: 117

Answers (2)

Ram
Ram

Reputation: 4779

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)

Upvotes: 0

Tasbiha
Tasbiha

Reputation: 106

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.

Upvotes: 2

Related Questions