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. Here is an example of how to create a 2D array with 3 rows and 4 columns, filled with zeroes:
# 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:
[[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:
This will also create 3x4 matrix with all elements as 0.