Search code examples
pythonpython-3.xappenddeque

Python deque append issue


I am trying to insert 2 items into the deque, each item will be having 2 points. Totally deque should contain 4 points. But it's appearing to be 8 points. Someone, please help me in avoiding these duplicate points to store in the item queue. Below is the code.

from collections import deque

class Data:
    Points = list()
    
class Point:
    Tag = ""
    
queue = deque()

item1 = Data()
item2 = Data()

point1 = Point()
point2 = Point()
point3 = Point()
point4 = Point()

point1.Tag = "point1"
point2.Tag = "point2"
point3.Tag = "point3"
point4.Tag = "point4"

item1.Points.append(point1)
item1.Points.append(point2)
item2.Points.append(point3)
item2.Points.append(point4)

queue.append(item1)
queue.append(item2)

for it in queue:
    for p in it.Points:
        print(p.Tag)

Solution

  • class Data:
        Points = list()
    

    Here, Points is a class attribute that is shared between instances! But you want it to be an instance attribute:

    class Data:
        def __init__(self):
            self.Points = list()
            # self.Points = []