In this article, we will discuss Python codes along with various examples of creating a matrix using for loop. The matrix consists of lists that are created and assigned to columns and rows. We will learn examples of 1D one dimensional, 2D two dimensional, and 3D Three dimensional matrix using Python list and for loop assignment.
Python code to create a matrix using for loop.
Python code implementation for 1D one dimensional matrix using for loop.
Code:
size_of_array = int(input("Enter size of 1D array: "))
#Declaring an empty 1D array.
a = []
#Initialize the Array
for i in range(0, size_of_array):
a.append(0)
#Printing the 1d dimensional created array
print(a)
Output:
Enter size of 1D array: 6 [0, 0, 0, 0, 0, 0]
Python code implementation for 2D two-dimensional matrix using for loop.
Code:
column_size = int(input("Enter size of column: "))
row_size = int(input("Enter size of row: "))
#Declaring an empty 1D array.
a = []
#Declaring an empty 1D array.
b = []
#Initialize the column.
for j in range(0, column_size):
b.append(0)
#Append the column to each row.
for i in range(0, row_size):
a.append(b)
#Printing the 2d created array
print(a)
Output:
Enter size of column: 4 Enter size of row: 3 [[0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0]]
Python code implementation for 3d three dimensional matrix using for loop.
Code:
first_dim_size = int(input("Enter size of first dim: "))
second_dim_size = int(input("Enter size of second dim: "))
third_dim_size = int(input("Enter size of third dim: "))
#Declaring an empty 1D array.
a = []
#Declaring an empty 1D array.
b = []
#Declaring an empty 1D array.
c = []
#Initialize the Third dim.
for i in range(0, third_dim_size):
a.append(0)
#Append the Third dim to Second dim
for j in range(0, second_dim_size):
b.append(a)
#Append the Second dim to First dim
for k in range(0, first_dim_size):
c.append(b)
#Printing the 3d created array
print(c)