List of objects with sublists

Hello, I’m trying to create a list of objects with sublists, here’s my example:

class testobj:
  def __init__(tst,lst = []):
    tst.lst = lst

newList = []
for i in range(10):
    newList.append(testobj())


for i in range(len(newList)):
    newList[i].lst.append(1)

but this returns

>>> newList[0].lst
[1, 1, 1, 1, 1, 1, 1, 1, 1, 1]

which is the not expected output (should return [1]).

If I do the same with a list of lists:

newList = []
for i in range(10):
    newList.append([])


for i in range(len(newList)):
    newList[i].append(1)

>>> newList[0]
[1]

Can someone help me spot the problem? Thanks

1 Like

You likely have an issue with your default argument (a common gotcha). The common practice is to
assign None:

Code

class testobj:
    
    def __init__(self, lst=None):
        if lst is None:
            self.lst = []
        else:
            self.lst = lst


new_list = []
...

Demo

new_list[0].lst

Also, try to use caps when naming classes, i.e. TestObj. :wink:

2 Likes