In this article, we will discuss the simplest method to create a 2D or two-dimensional array using Python. You can also implement this code using the function as well as classes.
Create empty 2d or two-dimensional array using Python
Python code implementation without user-defined functions & classes
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)
# 2D array is created.
#Print the two dimensional array.
print(a)
Output:
Enter size of column: 5 Enter size of row: 5 [[0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0]]
Python code implementation using the function
In this code, we will create a two-dimensional array using the function. We will take input from the user for row size and column size. We will pass the row size and column size to a function that will return the final two-dimensional array.
Code:
def create_2d_array(row_size, column_size):
#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)
return a
column_size = int(input("Enter size of column: "))
row_size = int(input("Enter size of row: "))
a = create_2d_array(row_size, column_size)
print(a)
Output:
Enter size of column: 4 Enter size of row: 5 [[0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0]] [[0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0]]
Python code implementation using Classes
In this code, we will create a two-dimensional array using classes. We will take input from the user for row size and column size and pass it while creating the object array_object. We will then call the function using array_object.create_2d_array(), the function will return the two-dimensional array created.
Code:
class two_d_array(object):
def __init__(self, row_size, column_size):
self.row_size = row_size
self.column_size = column_size
def create_2d_array(self):
#Declaring an empty 1D array.
a = []
#Declaring an empty 1D array.
b = []
#Initialize the column.
for j in range(0, self.column_size):
b.append(0)
#Append the column to each row.
for i in range(0, self.row_size):
a.append(b)
return a
column_size = int(input("Enter size of column: "))
row_size = int(input("Enter size of row: "))
#Create an Object:
array_object = two_d_array(row_size, column_size )
print(array_object.create_2d_array())