How to create a fix size list in python?

后端 未结 9 1841
不思量自难忘°
不思量自难忘° 2020-12-04 20:53

In C++, I can create a array like...

int* a = new int[10];

in python,I just know that I can declare a list,than append some items,or like..

9条回答
  •  时光说笑
    2020-12-04 21:30

    You can use this: [None] * 10. But this won't be "fixed size" you can still append, remove ... This is how lists are made.

    You could make it a tuple (tuple([None] * 10)) to fix its width, but again, you won't be able to change it (not in all cases, only if the items stored are mutable).

    Another option, closer to your requirement, is not a list, but a collections.deque with a maximum length. It's the maximum size, but it could be smaller.

    import collections
    max_4_items = collections.deque([None] * 4, maxlen=4)
    

    But, just use a list, and get used to the "pythonic" way of doing things.

提交回复
热议问题