Creating a Two Dimensional Array in Python

python中创建二维数组

Suppose you want to create an array with 4 rows and 3 columns.

Way 1


cols = 3
rows = 4

table = [[0] * cols for _ in range(rows)]

this code will give you:

 [[0, 0, 0], [0, 0, 0], [0, 0, 0], [0, 0, 0]]

Do not use the following code, this is a pitfall, never!

table = [[0] * cols ] * rows

Because, when you change one of the elements, say table[1][1], set it to 1, 4 elements will be changed at the same time!

In [41]: table = [[0] * cols ] * rows
    ...:

In [42]: table
Out[42]: [[0, 0, 0], [0, 0, 0], [0, 0, 0], [0, 0, 0]]

In [43]: table[1][1] = 1

In [44]: table
Out[44]: [[0, 1, 0], [0, 1, 0], [0, 1, 0], [0, 1, 0]]

Way 2

Using numpy package.

In [1]: import numpy as np
In [4]: np.zeros([4,3])
Out[4]: 
array([[0., 0., 0.],
       [0., 0., 0.],
       [0., 0., 0.],
       [0., 0., 0.]])