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:
arr = [] # <-- this line is entirely pointless
arr = [0 for i in range(5)]
Secondly, the two expressions
[0 for i in range(5)]
[0] * 5
create a new list
object, whereas
arr[0] = 0
mutates 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:
arr = []
arr.append(0)
arr.append(0)
to fill an initially empty list
incrementally.
Note that a Python list is not an Array
in, let's say, the Java sense that it has a predefined size. It is more like an ArrayList
.