pythonlistmultidimensional-array

How to define a two-dimensional array?


I want to define a two-dimensional array without an initialized length like this:

Matrix = [][]

But this gives an error:

IndexError: list index out of range


Solution

  • You're technically trying to index an uninitialized array. You have to first initialize the outer list with lists before adding items; Python calls this "list comprehension".

    # Creates a list containing 5 lists, each of 8 items, all set to 0
    w, h = 8, 5
    Matrix = [[0 for x in range(w)] for y in range(h)] 
    

    #You can now add items to the list:

    Matrix[0][0] = 1
    Matrix[6][0] = 3 # error! range... 
    Matrix[0][6] = 3 # valid
    

    Note that the matrix is "y" address major, in other words, the "y index" comes before the "x index".

    print Matrix[0][0] # prints 1
    x, y = 0, 6 
    print Matrix[x][y] # prints 3; be careful with indexing! 
    

    Although you can name them as you wish, I look at it this way to avoid some confusion that could arise with the indexing, if you use "x" for both the inner and outer lists, and want a non-square Matrix.