Reputation: 55
I want to create a list in python of a fixed size, let's so 3 to begin with. I have a method that writes data to this list every time the method is called, I want to add this to the list until the list is full, once the list is full it should start overwriting the data in the list in ascending order (e.g. starting with element 0). I also want to add a function which will increase the length of the array, i.e. if the method is called the array will increase from size 3 to size 4. How do I go about doing either of these?
Upvotes: 2
Views: 1958
Reputation: 55
Here is how I went about it in the end. I set a variable called length_list which was originally set at 3.
def add_to_list():
if len(list) < length_list:
append
else:
del list[0]
self.add_to_list()
def increase_length():
length_list += 1
Upvotes: 0
Reputation: 3159
This simple solution should do:
def add(l, item, max_len):
l.insert(0, item)
return l[:max_len]
l = ["banana", "peanut", "bicycle", "window"]
l = add(l, "monkey", 3)
print(newlist)
prints:
> ['monkey', 'banana', 'peanut']
The the list to edit (l
), the item to add and the max size (max_len
) of the list are arguments.
The item will then be added at index 0, while the list is limited to max_len.
Upvotes: 2
Reputation: 2665
This should do the trick. There are tons of prebuilt modules that have similar functionality but I thought it would be best if you could visualize the process!
class SizedList(list):
def __init__(self, size):
list().__init__(self)
self.__size = size
self.__wrap_location = 0
self.len = len(self)
def append(self, *args, **kwargs):
self.len = len(self)
if self.len >= self.__size:
if self.__wrap_location == self.__size-1:
self.__wrap_location = 0
self.__wrap_location += 1
self.pop(self.__wrap_location)
return self.insert(self.__wrap_location-1, *args)
return list.append(self, *args, **kwargs)
def increase_size(self, amount=1):
self.__size += 1
Upvotes: 2