Https://www.codecademy.com/courses/learn-python-3/lessons/inheritance-and-polymorphism/exercises/review-concepts

https://www.codecademy.com/courses/learn-python-3/lessons/inheritance-and-polymorphism/exercises/review-concepts

Hi,

with this lesson, I’m wondering why the last line of code (the print command) is not returning a sorted list, but just the list I entered.

class SortedList(list):

def append(self, value):

super().append(value)

self.sort()

print(SortedList([1,5,4,6]))

So currently your SortedList class only has an append() method, which appends a value and then sorts the list. This means that currently the list is only sorted when a value is appended, see below:

class SortedList(list):

  def append(self, value):
    super().append(value)
    self.sort()

list = SortedList([1,5,4,6])
list.append(4)

print(list)
# prints [1, 4, 4, 5, 6]

If you want the list to sort immediately, then you have to define the initialisation method for the class, or __init__(). Anything in this method is run as soon as a class member is initialised i.e. created. So if you want to sort the list on creation, you need to define this method first also calling your sort. Solution is blurred below in case you wish to try it yourself first.

class SortedList(list):

  def __init__(self, list):
    super().__init__(list)
    self.sort()

  def append(self, value):
    super().append(value)
    self.sort()

new_list = SortedList([1, 5, 4, 6])

print(new_list)
# prints [1, 4, 5, 6]

Ah, ok! That makes sense. Only when the method .append is called, the list gets sorted. Thanks!

one more question: how come this code does not sort the list? class SortedList(list):

def append(self, value):

super().append(value)

self.sort()

list = [1,5,4,6]

list.append(4)

print(SortedList(list))

Same situation here! The problem is that the list you have initialised is just that, a list! So the append() method used is simply the regular append method that’s always used with lists. You must initialise it first as a sorted list, and so that it uses the SortedList.append() method, like so:

list = SortedList([1, 5, 4, 6])
list.append(4)

print(list)
# prints [1, 4, 4, 5, 6]

Some things are so clear you just oversee them … Cheers again!

1 Like