Why does initializing the array arr work when it is done as a list comprehension (I think that is what the following example is --not sure), but not when each array location is initialized individually?
For example, this works: (a)
arr=[]
arr=[0 for i in range(5)]
but (b),
arr=[]
arr[0]=0
arr[1]=0
etc, doesn't.
Isn't the arr=[0 for i in range(5)] instruction essentially doing what is done in (b) above in one fell swoop?
I realize that array sizes need to be predefined (or allocated). So, I can understand something like
arr= [0]*5
or using numpy,
arr = np.empty(10, dtype=object)
work. However, I don't see how (a) preallocates the array dimension "ahead of time". How does python interpret (a) vs. (b) above?
Firstly, there is no point in declaring a variable if you rebind it later anyway:
Secondly, the two expressions
create a new
listobject, whereasmutates an existing one, namely it wants to reassign the first element of
arr. Since this doesn't exist, you will see an error. You could do instead:to fill an initially empty
listincrementally.Note that a Python list is not an
Arrayin, let's say, the Java sense that it has a predefined size. It is more like anArrayList.