## How to define a two-dimensional array?

### Question

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

``````Matrix = [][]
``````

but it does not work...

I've tried the code below, but it is wrong too:

``````Matrix = [5][5]
``````

Error:

``````Traceback ...

IndexError: list index out of range
``````

What is my mistake?

2020/08/20
1
747
8/20/2020 8:23:03 PM

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.

2019/08/05
1034
8/5/2019 7:18:59 PM

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]]
``````
2011/07/12

If you want to create an empty matrix, the correct syntax is

``````matrix = [[]]
``````

And if you want to generate a matrix of size 5 filled with 0,

``````matrix = [[0 for i in xrange(5)] for i in xrange(5)]
``````
2011/07/12

If all you want is a two dimensional container to hold some elements, you could conveniently use a dictionary instead:

``````Matrix = {}
``````

Then you can do:

``````Matrix[1,2] = 15
print Matrix[1,2]
``````

This works because `1,2` is a tuple, and you're using it as a key to index the dictionary. The result is similar to a dumb sparse matrix.

As indicated by osa and Josap Valls, you can also use `Matrix = collections.defaultdict(lambda:0)` so that the missing elements have a default value of `0`.

Vatsal further points that this method is probably not very efficient for large matrices and should only be used in non performance-critical parts of the code.

2017/11/12

In Python you will be creating a list of lists. You do not have to declare the dimensions ahead of time, but you can. For example:

``````matrix = []
matrix.append([])
matrix.append([])
matrix[0].append(2)
matrix[1].append(3)
``````

Now matrix[0][0] == 2 and matrix[1][0] == 3. You can also use the list comprehension syntax. This example uses it twice over to build a "two-dimensional list":

``````from itertools import count, takewhile
matrix = [[i for i in takewhile(lambda j: j < (k+1) * 10, count(k*10))] for k in range(10)]
``````
2011/07/12

You should make a list of lists, and the best way is to use nested comprehensions:

``````>>> matrix = [[0 for i in range(5)] for j in range(5)]
>>> pprint.pprint(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]]
``````

On your `[5][5]` example, you are creating a list with an integer "5" inside, and try to access its 5th item, and that naturally raises an IndexError because there is no 5th item:

``````>>> l = [5]
>>> l[5]
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
IndexError: list index out of range
``````
2017/11/12