Reserve memory for list in Python?

前端 未结 7 1008
北恋
北恋 2020-12-15 02:33

When programming in Python, is it possible to reserve memory for a list that will be populated with a known number of items, so that the list will not be reallocated several

7条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-12-15 03:15

    In most of everyday code you won't need such optimization.

    However, when list efficiency becomes an issue, the first thing you should do is replace generic list with typed one from array module which is much more efficient.

    Here's how list of 4 million floating point numbers cound be created:

    import array
    lst = array.array('f', [0.0]*4000*1000)
    

提交回复
热议问题