Python list limit size

To determine how many items a list has, use the len() function:

Print the number of items in the list:

thislist = ["apple", "banana", "cherry"]
print(len(thislist))

Try it Yourself »


Use the len() method to return the length of an array (the number of elements in an array).

Note: The length of an array is always one more than the highest array index.


Python list limit size

How to create a python list that can only contain a maximum number of elements

In this tutorial you will learn how to create a stack-like list class that can contain only a certain number of elements, any additional elements pushed to this list that cause it to exceed the limit will result in the elements at the tail of the stack being removed.

Creating our stack-like list object

The built-in list type in python can be used as a stack using the append() and pop() functions, the only additional functionality we would want to add on top is to have a maximum capacity to this list, so the easiest way to go about this would be to simply extend the built-in list class.

class MaxStack(list): def __init__(self, max_size): super().__init__() self.max_size = max_size def push(self, element): self.append(element) def append(self, element): super().append(element) if super().__len__() > self.max_size: super().__delitem__(0)

In the above code we are overriding the constructor to allow for a max_size argument, and the append method to handle the logic for removing excess elements. We also add a push method for this class to behave more like a stack (even though it acts only as an alias to append)

Using the list and exceeding the maximum number of elements

This object will behave much like a regular python list, simply instantiate it with the maximum number of desired elements, then you can start using it just like a normal list, however in this example we'll use our push() alias method

my_list = MaxStack(3) my_list.push(1) # my_list = my_list.push(2) # my_list = my_list.push(3) # my_list = my_list.push(4) # my_list = my_list.push(5) # my_list = list_head = my_list.pop() # my_list =

As you can see, you can append to this list normally until the limit is exceeded at which point the list will start trimming itself from the tail.

The pop() function still works as expected and will remove and return the element from the head of the list.

If your aim is to make this new object behave somewhat like a list, implement it as closely to a real Python list as possible by inheriting its behavior from the built-in list class. Then extend your class to add the behavior you want. Here's a partial implementation:

class MaxSizeList(list): def __init__(self, maxlen): self._maxlen = maxlen def append(self, element): self.__delitem__(slice(0, len(self) == self._maxlen)) super(MaxSizeList, self).append(element) a = MaxSizeList(3) print(a) a.append("hey") print(a) a.append("hi") print(a) a.append("let's") print(a) a.append("go") print(a)

Output:

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

Now, why do I say that this is a "partial" implementation? Because there are many ways to add elements to a list. For example, if you add these lines to the end of the above script:

a.extend(["some", "more", "stuff"]) print(a)

You'll see this output at the end:

['hi', "let's", 'go', 'some', 'more', 'stuff']

Oops. Your work is not done. We've overridden the append method, but not the extend method. And there are others, like __setslice__, __mul__, and so on.

Essentially, to create a complete implementation, you'd have to extend your class to provide implementations for every built-in method of the list class that could conceivably enlarge the length of the list. Do a dir(list) to see all its built-in "magic" methods, and figure out which ones you'd need to extend.

Thanks G-Do for your information, so NumPy eventually replaces Numeric and Numarray. Interesting!

When I was coding in C, I used to sample lab data and put it into a circular or ring buffer to keep the thing from overflowing. This was an easy way to calculate a moving average.

You can do a similar thing in Python using a list and keeping track of the index. When the index reaches the limit you have set, new data starts at index zero again.

A queue makes this simpler, particularly the deque container, because you can add to the end and pop the front. Here is an example, I hope you can see what is happening:

# the equivalent of a circular size limited list # also known as ring buffer, pops the oldest data item # to make room for newest data item when max size is reached # uses the double ended queue available in Python24 from collections import deque class RingBuffer(deque): """ inherits deque, pops the oldest data to make room for the newest data when size is reached """ def __init__(self, size): deque.__init__(self) self.size = size def full_append(self, item): deque.append(self, item) # full, pop the oldest item, left most item self.popleft() def append(self, item): deque.append(self, item) # max size reached, append becomes full_append if len(self) == self.size: self.append = self.full_append def get(self): """returns a list of size items (newest items)""" return list(self) # testing if __name__ == '__main__': size = 5 ring = RingBuffer(size) for x in range(9): ring.append(x) print ring.get() # test """ notice that the left most item is popped to make room result = [0] [0, 1] [0, 1, 2] [0, 1, 2, 3] [0, 1, 2, 3, 4] [1, 2, 3, 4, 5] [2, 3, 4, 5, 6] [3, 4, 5, 6, 7] [4, 5, 6, 7, 8] """