Search code examples
pythonlistmaxmaxlength

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?


Solution

  • 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?