How to define a two-dimensional array? How to define a two-dimensional array? python python

How to define a two-dimensional array?


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 0w, h = 8, 5Matrix = [[0 for x in range(w)] for y in range(h)] 

#You can now add items to the list:

Matrix[0][0] = 1Matrix[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 1x, 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.


If you really want a matrix, you might be better off using numpy. Matrix operations in numpy most often use an array type with two dimensions. There are many ways to create a new array; one of the most useful is the zeros function, which takes a shape parameter and returns an array of the given shape, with the values initialized to zero:

>>> import numpy>>> numpy.zeros((5, 5))array([[ 0.,  0.,  0.,  0.,  0.],       [ 0.,  0.,  0.,  0.,  0.],       [ 0.,  0.,  0.,  0.,  0.],       [ 0.,  0.,  0.,  0.,  0.],       [ 0.,  0.,  0.,  0.,  0.]])

Here are some other ways to create 2-d arrays and matrices (with output removed for compactness):

numpy.arange(25).reshape((5, 5))         # create a 1-d range and reshapenumpy.array(range(25)).reshape((5, 5))   # pass a Python range and reshapenumpy.array([5] * 25).reshape((5, 5))    # pass a Python list and reshapenumpy.empty((5, 5))                      # allocate, but don't initializenumpy.ones((5, 5))                       # initialize with ones

numpy provides a matrix type as well, but it is no longer recommended for any use, and may be removed from numpy in the future.


Here is a shorter notation for initializing a list of lists:

matrix = [[0]*5 for i in range(5)]

Unfortunately shortening this to something like 5*[5*[0]] doesn't really work because you end up with 5 copies of the same list, so when you modify one of them they all change, for example:

>>> matrix = 5*[5*[0]]>>> matrix[[0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0]]>>> matrix[4][4] = 2>>> matrix[[0, 0, 0, 0, 2], [0, 0, 0, 0, 2], [0, 0, 0, 0, 2], [0, 0, 0, 0, 2], [0, 0, 0, 0, 2]]