Let's say I have the following names and objects
original = n = <original_object>
n = n.next = <new_object>
After running the above I would expect to see original
pointing to <original_object>
, but that doesn't seem to be the case.
However, if I instead do:
original = n = <original_object>
n.next = <new_object> # Attribute of the object class
n = n.next
I then see original
pointing to <original_object>
(or at least that's what I think I see).
Concrete example
I'll illustrate this with a linked list in Python 3.8:
class Node:
def __init__(self, arg1):
self.next = None
With chain assignments:
head = n = Node(None)
n = n.next = Node(None)
print(head.next) # None (the "head" is gone?)
With consecutive assignments:
head = n = Node(None)
n.next = Node(None) # *
n = n.next # *
print(head.next) # <__main__.Node object at 0x7fa4e0610ca0>
My intention here is to preserve the "head" of the linked list as I add nodes at the tail. Why am I getting different results with chain vs consecutive assignments?