Initializing a list to a known number of elements in Python


Right now I am using a list, and was expecting something like:

verts = list (1000)

Should I use array instead?

10/28/2011 10:46:57 PM

Accepted Answer

The first thing that comes to mind for me is:

verts = [None]*1000

But do you really need to preinitialize it?

2/6/2009 7:02:00 PM

Not quite sure why everyone is giving you a hard time for wanting to do this - there are several scenarios where you'd want a fixed size initialised list. And you've correctly deduced that arrays are sensible in these cases.

import array

For the non-pythonistas, the (0,)*1000 term is creating a tuple containing 1000 zeros. The comma forces python to recognise (0) as a tuple, otherwise it would be evaluated as 0.

I've used a tuple instead of a list because they are generally have lower overhead.

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow