["python","list"]
How can I automatically limit the length of a list as new elements are added?

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.
You might want to use a collections.deque object with the maxlen constructor argument instead: >>> l = collections.deque(maxlen=5) >>> l.append('apple') >>> l.append('orange') >>> l.append('grape') >>> l.append('banana') >>> l.append('mango') >>> print(l) deque(['apple', 'orange', 'grape', 'banana', 'mango'], maxlen=5) >>> l.append('kiwi') >>> print(l) # only 5 items in list deque(['orange', 'grape', 'banana', 'mango', 'kiwi'], maxlen=5)