In python, an instance A can be revised by another one B after you let B=A? Why? [closed]

In the following code, I’m creating a head node of linked list. But I don’t know why the ‘.next’ of ‘head’ can be update(iterated) by update ‘tail’ and ‘tail.next’:

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

# For a given list, creat a head node of it
def creat_link_tail(val_list):
   head = Node(val_list[0])
   tail = head
   for ele in val_list[1:]:
     tail.next = Node(ele)
     tail = tail.next
return head

lkt = creat_link_tail([5, 3, 2, 6, 7])  #lkt 5->3->2->6->7

Answer

But I don’t know why the ‘.next’ of ‘head’ can be update(iterated) by update ‘tail’ and ‘tail.next’:

You stored the very fist element in head:

head = Node(val_list[0])

Then you assigned it as the initial value of tail:

tail = head

Now, tail and head points to the exact same object in memory which stores the same instance of Node(val_list[0]). To visualize this, we can inspect the memory used.

class Node(object):
   def __init__(self,x):
     self.val = x
     self.next = None

head = Node(0)
tail = head

print(id(head))  # Memory pointed to by head
print(id(tail))  # Memory pointed to by tail
print(head is tail)  # Checks if head is the same as tail

Output

22809434462432
22809434462432
True

As you can see, they are just point to the exact same object. They are different stack variables head and tail but their value points to the same object in heap. Thus accessing the pointed object via . from one variable e.g. tail.next = Node(ele) is like indirectly calling head.next = Node(ele).

Now let’s try to change the value of the stack variable tail and point it to another object.

tail = Node(0)

print(id(head))
print(id(tail))
print(head is tail)

Output

22809434462432
22809434463632
False

Now as you can see, the pointed object by head and tail are now different.