Python Forum

Full Version: List of objects with sublist
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Suppose I have the following code

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

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

>>> newList[0]
[1]
If however instead of having a list of lists, I have a list of objects containing a list attribute, the output is not the one I would expect:

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)
    
>>> newList[0].lst
[1, 1, 1, 1, 1, 1, 1, 1, 1, 1]
Can someone explain why? How would I make the list of objects behave correctly?
Thanks
you are using mutable default argument in the __init__

Read https://docs.python-guide.org/writing/go...-arguments
as a side note - don't use for i in range(len(newList)):, read https://python-forum.io/Thread-Basic-Nev...n-sequence
Ok thanks, but what's the syntax to do this in the constructor of the object?

EDT:

got it
class testobj:
  def __init__(tst,lst = None):
    tst.lst = []
if you do it like this, then it doesn't make sense to have lst argument at all - you can remove it

class testobj:
  def __init__(tst):
    tst.lst = []
by the way, convention is to use self. It's OK to use something different like tst but it make it more difficult for other developers to read