'Defect in linked list in Python

class Node:
   def __init__(self,data):
           self.data=data
           self.next=None   
head=Node(5)
trys=head
trys=trys.next
trys=Node(7)
print(head.next.data)

Here print would give error. Can you explain why?



Solution 1:[1]

The line trys=head creates a new variable which is pointed to head.

The line trys=trys.next re-assigns the variable trys to head.next.

The line trys=Node(7) re-assigns trys to Node(7). But the variable trys has no "memory" that it is "really" head.next - that is irrelevant. All we are doing here is re-assigning a variable named trys.

Thus, head.next remains unassigned, and therefore head.next.data will throw an error, because you are attempting to access a property of an undefined value.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1