Initializing a list to a known number of elements in Python
Rise to the top 3% as a developer or hire one of them at Toptal: https://topt.al/25cXVn
--------------------------------------------------
Track title: CC I Beethoven Sonata No 31 in A Flat M
--
Chapters
00:00 Initializing A List To A Known Number Of Elements In Python
00:18 Accepted Answer Score 399
00:35 Answer 2 Score 84
01:19 Answer 3 Score 69
01:42 Answer 4 Score 40
02:31 Answer 5 Score 29
04:07 Thank you
--
Full question
https://stackoverflow.com/questions/5216...
--
Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...
--
Tags
#python #arrays #list
#avk47
ACCEPTED ANSWER
Score 400
The first thing that comes to mind for me is:
verts = [None]*1000
But do you really need to preinitialize it?
ANSWER 2
Score 84
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.
ANSWER 3
Score 69
One obvious and probably not efficient way is
verts = [0 for x in range(1000)]
Note that this can be extended to 2-dimension easily. For example, to get a 10x100 "array" you can do
verts = [[0 for x in range(100)] for y in range(10)]
ANSWER 4
Score 40
Wanting to initalize an array of fixed size is a perfectly acceptable thing to do in any programming language; it isn't like the programmer wants to put a break statement in a while(true) loop. Believe me, especially if the elements are just going to be overwritten and not merely added/subtracted, like is the case of many dynamic programming algorithms, you don't want to mess around with append statements and checking if the element hasn't been initialized yet on the fly (that's a lot of code gents).
object = [0 for x in range(1000)]
This will work for what the programmer is trying to achieve.