0

I am trying to create a two dimensional array in python. However I am confused about the requirement for initializing an array. This question is related to How to define a two-dimensional array in Python

When I use a list comprehension as:

out = [[ i*j for j in range (Y)] for i in range (X)]
print (out)

Here I don't need to initialize any array. However in the second case:

out = []
for i in range (X):
    for j in range (Y):
        out[i][j] = i*j

This doesn't work without first initializing the array as:

out = [[ 0 for j in range (Y)] for i in range (X)]

I understand the need for initializing the array in the second case, but could someone please explain how does it work in the first case.

Muradin
  • 3
  • 4

2 Answers2

0

A list comprehension is a single statement that initializes an array with some data, so you don't need another initialization. In the second case, you need to first initialize the array before assigning values to its elements.

Mureinik
  • 297,002
  • 52
  • 306
  • 350
0

The statement out = [] creates an empty list: when you try to access an item in that list by index, using out[3] = foo, you're saying 'get me the 3rd element of out and set it to foo'. But an empty list has no 3rd element yet - you need to add the elements, then assign values to them.

In this case, the easiest thing is to assign zero values to your array, then overwrite them with the values of i*j:

out = [0]*X # <- initialise outer list
for i in range (X):
    out[i] = [0]*Y # <- initialise each row of inner list
    for j in range (Y):
        out[i][j] = i*j

print(out)
Richard Inglis
  • 5,888
  • 2
  • 33
  • 37