# How to define a two-dimensional array?

## 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?

### Accepted Answer

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.

### Popular Answer

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 reshape
numpy.array(range(25)).reshape((5, 5)) # pass a Python range and reshape
numpy.array([5] * 25).reshape((5, 5)) # pass a Python list and reshape
numpy.empty((5, 5)) # allocate, but don't initialize
numpy.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.

Read more... Read less...

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]]
```

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)]
```

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.

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)]
```

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
```