Izana
Izana

Reputation: 3115

python assignment order in expression

# class defined here.
class ListNode(object):
    def __init__(self, x):
        self.val = x
        self.next = None

# A function here.
def list_init(lst):
    if not lst:
        return None

    root = ListNode(lst[0])
    temp = root
    for i in range(1, len(lst)):
        temp.next = ListNode(lst[i]) #
        temp = temp.next # these two lines I want to simplify
    return root

when I simplify the two lines as

temp = temp.next = ListNode(lst[i])

Thing's going wrong and the root.next is None.

What's the difference between these two way of assignment expression?

I think they are the same, but the result is not the same.

However, I change the statement into

temp.next = temp = ListNode(lst[i])

the result is correct, confused.

Upvotes: 1

Views: 78

Answers (1)

Ignacio Vazquez-Abrams
Ignacio Vazquez-Abrams

Reputation: 798804

The assignment statement binds all names to the same object on the RHS. Use tuple unpacking if you want to handle multiple objects properly.

temp, temp.next = temp.next, ListNode(lst[i])

Upvotes: 1

Related Questions