In this article, we will learn how to initialize a 2D array (two-dimensional array or list) using Python. We will initialize different sizes of array/matrix/list.
Initialize 2D array of size 3×3 in Python
Code:
#Initialize 2D array of size 3x3 in Python
column_size = 3
row_size = 3
#Declaring an empty 1D array.
a = []
#Declaring an empty 1D array.
b = []
#Initialize the column.
for j in range(0, column_size):
b.append(j)
#Append the column to each row.
for i in range(0, row_size):
a.append(b)
# 2D array is created.
#Print the two dimensional list of size 3x3 in Python
print(a)
Output
[[0, 1, 2], [0, 1, 2], [0, 1, 2]]
Initialize 2D array of size 4×5 in Python
Code:
#Initialize 2D array of size 4x5 in Python
column_size = 5
row_size = 4
#Declaring an empty 1D array.
a = []
#Declaring an empty 1D array.
b = []
#Initialize the column.
for j in range(0, column_size):
b.append(j)
#Append the column to each row.
for i in range(0, row_size):
a.append(b)
# 2D array is created.
#Print the two dimensional list of size 4x5 in Python
print(a)
Output:
[[0, 1, 2, 3, 4], [0, 1, 2, 3, 4], [0, 1, 2, 3, 4], [0, 1, 2, 3, 4]]
Initialize 2D array of size 10×10 in Python
Code:
#Initialize 2D array of size 10x10 in Python
column_size = 10
row_size = 10
#Declaring an empty 1D array.
a = []
#Declaring an empty 1D array.
b = []
#Initialize the column.
for j in range(0, column_size):
b.append(j)
#Append the column to each row.
for i in range(0, row_size):
a.append(b)
# 2D array is created.
#Print the two dimensional list of size 10x10 in Python
print(a)
.
Output
[[0, 1, 2, 3, 4, 5, 6, 7, 8, 9], [0, 1, 2, 3, 4, 5, 6, 7, 8, 9], [0, 1, 2, 3, 4, 5, 6, 7, 8, 9], [0, 1, 2, 3, 4, 5, 6, 7, 8, 9], [0, 1, 2, 3, 4, 5, 6, 7, 8, 9], [0, 1, 2, 3, 4, 5, 6, 7, 8 , 9], [0, 1, 2, 3, 4, 5, 6, 7, 8, 9], [0, 1, 2, 3, 4, 5, 6, 7, 8, 9], [0, 1, 2, 3, 4, 5, 6, 7, 8, 9], [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]]