-1

I want to append an element to a single object in a list, but that object appends to all elements of the list.

class A:
   list_of_B=[]

class B:
   name = ""

list_a = [A() for i in range(3)]
list_b = [B() for j in range(7)]

list_b[0] = "1"
list_b[1] = "2"
list_b[2] = "3"

list_a[2].list_of_B.append(list_b[1])

My problem is that the element list_b[1] appends to all the element in list_a not just for the element lista_a[2].

1 Answers1

2

list_of_B is a class variable, change it to an instance variable

class A:
    def __init__(self):
        self.list_of_B = []
C.B.
  • 8,096
  • 5
  • 20
  • 34