Right now I am using a list, and was expecting something like:
verts = list (1000)
Should I use array instead?
Right now I am using a list, and was expecting something like:
verts = list (1000)
Should I use array instead?
The first thing that comes to mind for me is:
verts = [None]*1000
But do you really need to preinitialize it?
You could do this:
verts = list(xrange(1000))
That would give you a list of 1000 elements in size and which happens to be initialised with values from 0-999. As list does a __len__ first to size the new list it should be fairly efficient.
You should consider using a dict type instead of pre-initialized list. The cost of a dictionary look-up is small and comparable to the cost of accessing arbitrary list element.
And when using a mapping you can write:
aDict = {}
aDict[100] = fetchElement()
putElement(fetchElement(), fetchPosition(), aDict)
And the putElement function can store item at any given position. And if you need to check if your collection contains element at given index it is more Pythonic to write:
if anIndex in aDict:
print "cool!"
Than:
if not myList[anIndex] is None:
print "cool!"
Since the latter assumes that no real element in your collection can be None. And if that happens - your code misbehaves.
And if you desperately need performance and that's why you try to pre-initialize your variables, and write the fastest code possible - change your language. The fastest code can't be written in Python. You should try C instead and implement wrappers to call your pre-initialized and pre-compiled code from Python.
Without knowing more about the problem domain, it's hard to answer your question. Unless you are certain that you need to do something more, the pythonic way to initialize a list is:
verts = []
Are you actually seeing a performance problem? If so, what is the performance bottleneck? Don't try to solve a problem that you don't have. It's likely that performance cost to dynamically fill an array to 1000 elements is completely irrelevant to the program that you're really trying to write.
The array class is useful if the things in your list are always going to be a specific primitive fixed-length type (e.g. char, int, float). But, it doesn't require pre-initialization either.