W3docs

How to initialize a two-dimensional array in Python?

You can use the built-in list function to create a 2D array (also known as a list of lists) in Python.

You can use the built-in list function to create a 2D array (also known as a list of lists) in Python. Here is an example of how to create a 2D array with 3 rows and 4 columns, filled with zeroes:

Create a 2-D array in Python using built-in list

# create a 2D array with 3 rows and 4 columns, filled with zeroes
rows = 3
cols = 4
arr = [[0 for j in range(cols)] for i in range(rows)]

print(arr)

This will output:

2-D array printed in Python

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

Alternatively, you can use numpy library, which is best suited for numerical calculations. Here's an example:

Create a 2-D array with numpy

import numpy as np
arr = np.zeros((3,4))
print(arr)

This will also create 3x4 matrix with all elements as 0.