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..
l = [1,2,3,4]
l = range(10)
Can I initialize a list by a given size,like c++,and do not do any assignment?
(tl;dr: The exact answer to your question is
numpy.emptyornumpy.empty_like, but you likely don’t care and can get away with usingmyList = [None]*10000.)Simple methods
You can initialize your list to all the same element. Whether it semantically makes sense to use a non-numeric value (that will give an error later if you use it, which is a good thing) or something like 0 (unusual? maybe useful if you’re writing a sparse matrix or the ‘default’ value should be 0 and you’re not worried about bugs) is up to you:
(Here
_is just a variable name, you could have usedi.)You can also do so like this:
You probably don’t need to optimize this. You can also append to the array every time you need to:
Performance comparison of simple methods
Which is best?
Results in python2.7:
Results in python 3.2:
As we can see, it is likely better to do the idiom
[None]*10000in both python2 and python3. However, if one is doing anything more complicated than assignment (such as anything complicated to generate or process every element in the list), then the overhead becomes a meaninglessly small fraction of the cost. That is, such optimization is premature to worry about if you’re doing anything reasonable with the elements of your list.Uninitialized memory
These are all however inefficient because they go through memory, writing something in the process. In C this is different: an uninitialized array is filled with random garbage memory (sidenote: that has been reallocated from the system, and can be a security risk when you allocate or fail to mlock and/or fail to delete memory when closing the program). This is a design choice, designed for speedup: the makers of the C language thought that it was better not to automatically initialize memory, and that was the correct choice.
This is not an asymptotic speedup (because it’s
O(N)), but for example you wouldn’t need to first initialize your entire memory block before you overwrite with stuff you actually care about. This, if it were possible, is equivalent to something like (pseudo-code)x = list(size=10000).If you want something similar in python, you can use the
numpynumerical matrix/N-dimensional-array manipulation package. Specifically,numpy.emptyornumpy.empty_likeThat is the real answer to your question.