Search code examples
pythonpython-3.xlistclassclass-instance-variables

Why the list variable named nodes in the class is taking the output of the previous instance of the class?


class Node:
    def __init__(self, value):
        self.data = value
        self.next = None
        
class SinglyLinkedList:
    nodes = []
    
    def __init__(self):
        self.head = None
        self.tail = None
    
    def insertHead(self, value):
        node = Node(value)
        
        if(self.head is None):
            self.head = node
            self.tail = node
            return
        
        node.next = self.head
        self.head = node
        
    def insertTail(self, value):
        node = Node(value)
        
        if(self.tail is None):
            self.head = node
            self.tail = node
            return
        
        self.tail.next = node
        self.tail = node
    
    def displayNodes(self):
        temp = self.head
        
        while (temp is not None):
            self.nodes.append(temp.data)
            temp = temp.next
            
        return self.nodes    
        
### Object 1
obj1 = SinglyLinkedList()
obj1.insertHead(8)
obj1.insertHead(7)
obj1.insertHead(5)
obj1.insertTail(30)
print(obj1.displayNodes())

### Object 2
obj2 = SinglyLinkedList()
obj2.insertHead(20)
obj2.insertHead(10)
print(obj2.displayNodes())

### Object 3
obj3 = SinglyLinkedList()
obj3.insertHead(50)
obj3.insertHead(22)
obj3.insertHead(19)
print(obj3.displayNodes())
print(obj3.nodes)

### Object 4
obj4 = SinglyLinkedList()
obj4.insertHead(45)
obj4.insertHead(40)
obj4.insertHead(35)
obj4.insertHead(28)
print(obj4.displayNodes())

Output

python flatten_LL.py
[5, 7, 8, 30]
[5, 7, 8, 30, 10, 20]
[5, 7, 8, 30, 10, 20, 19, 22, 50]
[5, 7, 8, 30, 10, 20, 19, 22, 50]
[5, 7, 8, 30, 10, 20, 19, 22, 50, 28, 35, 40, 45]

This the code of a singly linked list. I have created four instances and i am storing the linked list value in the list variable named "nodes". For each instance i am returning that list variable "nodes". As you can see the output, from the second instance, display of the nodes the output of the previous instance is still staying as it is. I want to know why this is happenning, as for each instance the storage is allocated to that instance separately.


Solution

  • Because nodes is (essentially) a static variable.

    You probably meant to write this:

    class SinglyLinkedList:    
        def __init__(self):
            self.nodes = []
            self.head = None
            self.tail = None