So I have an array that holds several numbers. As my script runs, more and more numbers are appended to this array. However, I am not interested in all the numbers but just want to keep track of the last 5 numbers.
Currently, I just store all the numbers in the array. However, this array gets really big and it’s full of unnecessary information.
I have thought about making a function that when it adds an element to the array, also removes the last element if the array already contains 5 numbers.
I also thought about making a new class to create a data structure that does what I want. However, I only need to reference this array occasionally and is only a small part of the script. So I think it is overkill if I create a whole new class to do this.
What is the best way to do this?
Try using a deque:
http://docs.python.org/library/collections.html#deque-objects
“If maxlen is not specified or is None, deques may grow to an arbitrary length. Otherwise, the deque is bounded to the specified maximum length. Once a bounded length deque is full, when new items are added, a corresponding number of items are discarded from the opposite end. Bounded length deques provide functionality similar to the tail filter in Unix. They are also useful for tracking transactions and other pools of data where only the most recent activity is of interest.”