Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set a max length for a python list/set?

In c/c++, we could have:

maxnum = 10;
double xlist[maxnum];

How to set a maximum length for a python list/set?

like image 417
alvas Avatar asked Jul 08 '13 12:07

alvas


People also ask

How do I set the maximum length of a list?

How to set a maximum length for a python list/set? One approach is to create custom class of list and inherit functionality from python list . Then in add (and maybe others) methods add a check for max length. @stalk you should post that as an answer.

Can you limit the size of a list in Python?

Maximum length of a list is platform dependent and depends upon address space and/or RAM. The maxsize constant defined in sys module returns 263-1 on 64 bit system. The largest positive integer supported by the platform's Py_ssize_t type, is the maximum size lists, strings, dicts, and many other containers can have.

How do you increase the length of a list in Python?

The . extend() method increases the length of the list by the number of elements that are provided to the method, so if you want to add multiple elements to the list, you can use this method.

What is the maximum size of a set in Python?

It is the Python platform's pointer that dictates the maximum size of lists and strings in Python. The size value returned by maxsize depends on the platform architecture: 32-bit: the value will be 2^31 – 1, i.e. 2147483647. 64-bit: the value will be 2^63 – 1, i.e. 9223372036854775807.


2 Answers

You don't and do not need to.

Python lists grow and shrink dynamically as needed to fit their contents. Sets are implemented as a hash table, and like Python dictionaries grow and shrink dynamically as needed to fit their contents.

Perhaps you were looking for collections.deque (which takes a maxlen parameter) or something using a heapq (using heapq.heappushpop() when you have reached the maximum) instead?

like image 183
Martijn Pieters Avatar answered Oct 10 '22 16:10

Martijn Pieters


Here is extended version of python's list. It behaves like list, but will raise BoundExceedError, if length is exceeded (tried in python 2.7):

class BoundExceedError(Exception):
    pass


class BoundList(list):
    def __init__(self, *args, **kwargs):
        self.length = kwargs.pop('length', None)
        super(BoundList, self).__init__(*args, **kwargs)

    def _check_item_bound(self):
        if self.length and len(self) >= self.length:
            raise BoundExceedError()

    def _check_list_bound(self, L):
        if self.length and len(self) + len(L) > self.length:
            raise BoundExceedError()

    def append(self, x):
        self._check_item_bound()
        return super(BoundList, self).append(x)

    def extend(self, L):
        self._check_list_bound(L)
        return super(BoundList, self).extend(L)

    def insert(self, i, x):
        self._check_item_bound()
        return super(BoundList, self).insert(i, x)

    def __add__(self, L):
        self._check_list_bound(L)
        return super(BoundList, self).__add__(L)

    def __iadd__(self, L):
        self._check_list_bound(L)
        return super(BoundList, self).__iadd__(L)

    def __setslice__(self, *args, **kwargs):
        if len(args) > 2 and self.length:
            left, right, L = args[0], args[1], args[2]
            if right > self.length:
                if left + len(L) > self.length:
                    raise BoundExceedError()
            else:
                len_del = (right - left)
                len_add = len(L)
                if len(self) - len_del + len_add > self.length:
                    raise BoundExceedError()
        return super(BoundList, self).__setslice__(*args, **kwargs)

Usage:

>>> l = BoundList(length=10)
>>> l.extend([1, 2, 3, 4, 5, 6, 7, 8, 9, 10])
>>> l
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
>>> # now all these attempts will raise BoundExceedError:
>>> l.append(11)
>>> l.insert(0, 11)
>>> l.extend([11])
>>> l += [11]
>>> l + [11]
>>> l[len(l):] = [11]
like image 20
stalk Avatar answered Oct 10 '22 17:10

stalk