![]() |
List of objects with sublist - Printable Version +- Python Forum (https://python-forum.io) +-- Forum: Python Coding (https://python-forum.io/forum-7.html) +--- Forum: General Coding Help (https://python-forum.io/forum-8.html) +--- Thread: List of objects with sublist (/thread-24728.html) |
List of objects with sublist - medatib531 - Mar-01-2020 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 RE: List of objects with sublist - buran - Mar-01-2020 you are using mutable default argument in the __init__ Read https://docs.python-guide.org/writing/gotchas/#mutable-default-arguments RE: List of objects with sublist - buran - Mar-01-2020 as a side note - don't use for i in range(len(newList)): , read https://python-forum.io/Thread-Basic-Never-use-for-i-in-range-len-sequence
RE: List of objects with sublist - medatib531 - Mar-01-2020 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 = [] RE: List of objects with sublist - buran - Mar-01-2020 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
|