Alex Rivera | Logout

How can I automatically limit the length of a list as new elements are added?

Asked 2011-05-10T03:04:47.343
101

I want to create a list that will contain the last 5 values entered into it.

Here is an example:

>>> l = []
>>> l.append('apple')
>>> l.append('orange')
>>> l.append('grape')
>>> l.append('banana')
>>> l.append('mango')
>>> print(l)
['apple', 'orange', 'grape', 'banana', 'mango']
>>> l.append('kiwi')
>>> print(l)  # only 5 items in list
['orange', 'grape', 'banana', 'mango', 'kiwi']

So, in Python, is there any way to achieve what is demonstrated above? The variable does not need to be a list, I just used it as an example.

Edit
Report

1 Answer

0

Most often when you need such a kind of facility, you would write a function which takes the list and then returns the last five elements.

>>> l = range(10)
>>> l[-5:]

But if you really want a custom list, having a cap on five elements, you can override the built-in list and it's methods, you would do something like this, for all it's methods.

class fivelist(list):
    def __init__(self, items):
        list.__init__(self, items[-5:])

    def insert(self, i, x):
        list.insert(self, i, x)
        return self[-5:]

    def __getitem__(self, i):
        if i > 4:
           raise IndexError
        return list.__getitem__(self, i)

    def __setitem__(self, i, x):
        if 0<= i <= 4:
          return list.__setitem__(self, i, x)
        else:
          raise IndexError
answered 2011-05-10T03:19:21.600

Your Answer