Python class to implement a list with a size limit I am currently working through a python course about objected oriented programming. I was given this first assignment to work on:


  Create a simple class, MaxSizeList, that acts a little bit like a
  list, with a pre-configured limit on its size.  
  
  Here some test calling code that imports the completed MaxSizeList and
  then uses it to create two new MaxSizeList objects.  

from assignments import MaxSizeList  # assumes "class MaxSizeList"
                                     # is in a script called "assignments.py"

  
  Below are the test cases:

a = MaxSizeList(3)
b = MaxSizeList(1)

a.push("hey")
a.push("hi")
a.push("let's")
a.push("go")

b.push("hey")
b.push("hi")
b.push("let's")
b.push("go")

print(a.get_list())
print(b.get_list())



Output


 # ['hi', "let's", 'go']
 # ['go']



I came up with this code which outputs the correct result:

class MaxSizeList(object):

    ls = []

    def __init__(self,mx):
        self.val = mx


    def push(self,st):
        self.ls.append(st)



    def get_list(self):
        while len(self.ls) != self.val:
            self.ls.pop(0)
        return self.ls


Do you have any input on how this can be done more efficiently? Did I do it correctly or is there anything to note from the code I came up with?
Below,  I have slightly recast your class.  In those changes are incorporated two suggestions.

1) If limiting the size of the structure, do it at the input:

I removed the length check from get_list() and moved it to push()

2) Class attributes are not instance attributes:

You code had a bug whereby the ls attribute was declared on the class and not  on the instance. In the case of:

class MaxSizeList(object):

    ls = []


ls will be shared will all instances of MaxSizeList.  What you need is actually:

class MaxSizeList(object):

    def __init__(self, max_length):
        self.ls = []


In this case, every instance will get its own ls. 

I am going to guess that this is why you needed to do the limiting on the output and not on the input.  That combined with using the same test data for the a and the b instance allowed your test cases to pass even with a substantial bug.

Code:

class MaxSizeList(object):

    def __init__(self, max_length):
        self.max_length = max_length
        self.ls = []

    def push(self, st):
        if len(self.ls) == self.max_length:
            self.ls.pop(0)
        self.ls.append(st)

    def get_list(self):
        return self.ls