Suppose you want to create an array with 4 rows and 3 columns.
Method 1: Using List Comprehension
cols = 3
rows = 4
table = [[0] * cols for _ in range(rows)]
This code creates:
[[0, 0, 0], [0, 0, 0], [0, 0, 0], [0, 0, 0]]
Do not use the following code (common pitfall):
table = [[0] * cols] * rows
If you modify one element, all rows will be affected because they reference the same list:
table = [[0] * cols] * rows
table[1][1] = 1
print(table)
# Output: [[0, 1, 0], [0, 1, 0], [0, 1, 0], [0, 1, 0]]
Method 2: Using NumPy
import numpy as np
table = np.zeros((4, 3))
print(table)
# Output:
# [[0. 0. 0.]
# [0. 0. 0.]
# [0. 0. 0.]
# [0. 0. 0.]]
Additional Tips
- For non-zero initialization, replace
0with any value you need. - For jagged (non-rectangular) arrays, use a list of lists with different lengths.
- NumPy arrays are recommended for numerical computations and large data due to better performance and more features.