Search code examples
pythonpython-3.xlistoopsuper

How do I create a Subclass of the "list" class, that sorts itself upon instantiation?


I want to create SortedList, a subclass of the list class.
I want SortedList to sort itself upon instantiation.

For example, with this input:

x = SortedList([1, 9, 7])
print(x)

I would want this output:

[1, 7, 9]

I'm a begginer. I know there might some function or data type that's better for this, but I want to practice my dunder methods and OOP skills.

I tried this, but it's not working:

class SortedList(list):
    def __init__(self, values):
        super().__init__()
        self.values = values
        self.sort(self.values)

I'm a bit confused.

I've used super() before, but I used it with superclasses that I made, where I knew the attributes. This time, I have to use super() with a built-in class, so I'm not sure what attributes to write.

Please help.
Thanks!


Solution

  • Use this:

    class SortedList(list):
        def __init__(self, values):
            super().__init__(sorted(values))
    
    x = SortedList([1, 9, 7])
    print(x)
    

    A list can be built from an iterable, from an array for instance. We can thus pass a sorted copy of the values to the super constructor and let it initialize its attributes (we don't have to know the internals of list).

    Note that if you really want to implement a SortedList, you'll have to keep on overriding the other methods!