1
# 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.

3
  • 2
    Even if it was the same, why would you even do that? It's not clear to me whether temp.next gets set first, or temp get set first. You shouldn't rely on people knowing the particularity of how the languages chooses to implement stuff like this. Commented Nov 21, 2015 at 0:30
  • I think you are right. But I think the assignment of value is from the right to the left, so the temp.next gets first, IMO. Commented Nov 21, 2015 at 0:36
  • I think I work it out: temp = temp.next = ListNode(lst[i]) is equal to temp = ListNode(lst[i]), temp.next = ListNode(lst[i]). That's why I get the wrong ans. It's different with C. In python, it's from left. Commented Nov 21, 2015 at 1:04

1 Answer 1

1

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])
Sign up to request clarification or add additional context in comments.

5 Comments

I tried your code, still wrong with: AttributeError: 'NoneType' object has no attribute 'next', meaning root.next is still None.
@Izana: That's because your initial goal was impossible in the first place. Those two assignments must occur in that order.
May you explain what is RHS? Thx. From the way of tuple unpacking, it's impossible. But when I change the order into temp.next = temp = ListNode(lst[i]), the result is right. It's more confusing.
And when you run the first unsimplified code, the temp and temp.next are all binds to the same obj ListNode(lst[i]). It is equal to the "binds all names to the same object on the RHS", I think.
I think u r right, and I think find out what's wrong in there. The expression first binds the temp with ListNode(lst[i]), so the value of temp is changed, and the temp of temp.next is the updated temp instead of the old temp value.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.