views:

4824

answers:

6

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

verts = list (1000)

Should I use array instead?

+16  A: 

The first thing that comes to mind for me is:

verts = [None]*1000

But do you really need to preinitialize it?

Steve Losh
Yes, because I know the number of elements.
Joan Venge
that's not a 'need', just a (premature?) optimisation
Javier
It's not a premature optimization if you are writing new code.
Joan Venge
That's like saying, don't care about performance, just write it.
Joan Venge
Yes, that's exactly the point. "Premature optimization is the root of all evil" just means that you should write code without caring about performance - at first. If you find that the code is running slow later on, *then* go back and make optimizations like this one.
David Zaslavsky
I think you are wrong. Premature optimization happens when you try to change something that already works.You should always write the fastest code possible.
Joan Venge
No, premature optimization is when you try to optimize code that you aren't certain needs to be optimized. You should NOT always write the fastest code possible -- other concerns like business goals, maintainance cost, engineering time to write it, are often more important.
Even your phrase validates mine. When you try to optimize code. Well in my case, since there is NO code, obviously I can't do any premature optimization.
Joan Venge
To quote a friend of mine, Peter Ritchie: "That's the biggest misinterpretation of a misinterpreted quote. It was Hoare, and the quote is: "We should forget about small efficiencies, say about 97% of the time: premature optimization is the root of all evil."The intention is
Joan Venge
that small changes for small improvements in performance don't justify the introduced instability. But, when writing original code, it should always be written with the most performant algorithm.
Joan Venge
"We should forget about small efficiencies" - Preinitializing a list of 1000 is premature.
Richard Levasseur
1000 is just an example.
Joan Venge
Note that there are other legitimate cases than optimizations for the wish to pre-allocate an array. It could be the code that uses it doesn't add elements, just replaces existing ones, so it's more like an array than a list.
Lasse V. Karlsen
Maybe it's not about optimization. For example in Dynamic Programming a pre-initialized list is useful. (Array would be better though.)
Georg
A: 

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.

You don't see the point. I just want to create an list/array with a predefined number of elements. Commenting on why and how I should need is silly. I know what I am doing. Thanks.
Joan Venge
if you knew what you are doing, you would be aware that sequence types overload the * operator
hop
When I said, I know what I am doing, I meant programming wise, not python. If I knew python, I wouldn't ask the question, now would I?
Joan Venge
Can you edit the question and explain a bit more of the context? From the question, it's not clear what the right answer is, and it's also not clear that you know what you're doing.
let's say he wants to implement merge sort. He's weird, isn't he.
Victor Ionescu
+1  A: 

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.

Abgan
A: 

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.

John Montgomery
before python 3.0 it would be range(1000); in python 3.0 it would be list(range(1000))
hop
+1  A: 

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
verts=array.array('i',(0,)*1000)

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.

FoxyLad
Some people take "premature" optimization literally I guess.
Joan Venge
A: 

It feels like the some of the most basic language constructs in python is just missing. Inititlizing an array, giving it a predetermined size shouldn't be something out of the ordinary. Most langauges can do that. Very strange indeed! I also foudn that enumerations is not built in to the languagr either, are people indexing their arrays using constant numeric? Building strange classes and stuff for these simple things is just stupid. Crappy language.

Larswad