Define two-dimensional array in Python

Problem description

How to create an empty two-dimensional array in Python?

Problrm solution

There are two ways to create two-dimensional arrays/martices:

  • using clear Python
  • using numpy module

Using clear Python

First of all, you have to innitialize the outer list with lists, so-called list comprehension:

w = 6 # width, number of columns 
h = 4 # height, number of rows 

array = [[0 for x in range(w)] for y in range(h)]

Now, you can add items to the list:

array[0][0] = 1
array[2][5] = 9

REMEMBER Be careful with idexing, you can't go out of range!

array[2][2] = 5 # valid
array[7][2] = 3 # error

Using numpy module

This way is much easier. You can use zeros function from numpy to create 2D array with all values set to zero:

import numpy 

array = numpy.zeros((4,4))

REMEMBER Even though the second version is easier, the first one is better for this operation unless we need any matrix operations.

We collect traffic information to improve the site.

Anonymous analytics only. No ads, no cross-site tracking.

Learn more