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

alvas picture alvas · Jul 8, 2013 · Viewed 39.7k times · Source

In c/c++, we could have:

maxnum = 10;
double xlist[maxnum];

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

Answer

Martijn Pieters picture Martijn Pieters · Jul 8, 2013

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?