A 2D array can be defined as an array of arrays. The 2D array is organized as matrices which can be represented as the collection of rows and columns.
However, 2D arrays are created to implement a relational database look alike data structure. It provides ease of holding bulk data at once which can be passed to any number of functions wherever required. It is important to knowhow to create a 2D array in python as 2D arrays are very commonly used data-structures.
In this article,we are going to explore two approaches regarding how to make 2D arrays in python.
Approaches for creating 2D array in python
- Naive Method for creating 2D array in python
- Using Empty List Method for creating 2D array in python
- Using List Comprehension for creating 2D array in python
Approach-1: Naive Method for creating 2D array in python
In this method,we fix the number of rows and cols beforehand and use it to create a 2d array.
Here In example,we create a 3×3 2d array by initializing it with 0’s and finally print the array.
Code:
#declare rows and cols
rows, cols = (3,3)
#create an array
arr = [[0]*cols]*rows
print(arr)
Output:
[[0, 0, 0], [0, 0, 0], [0, 0, 0]]
Explanation:
- The number of rows and cols should be specified by the user.
- The size of the 1D list is equal to the number of cols and then multiplied with the number of rows it results in the creation of a 2D list.
Approach-2: Empty List Method for creating 2D array in python
In this method,we use an empty list and append lists of data into it sequentially.This results in formation of a 2d array.
Here in the example,we create a 3×3 2d array by using empty lists and appending lists of rows into it.
Code:
arr=[]
#declare rows and cols
rows, cols=3,3
#Iterate over the rows
for i in range(rows):
#make an empty list of col
col = []
#add col values to the list
for j in range(cols):
col.append(0)
#append the col list to arr list
arr.append(col)
#display the 2d array
print(arr)
Output:
[[0, 0, 0], [0, 0, 0], [0, 0, 0]]
Explanation:
- Here zeros are appended as elements for number of column times and then appending this 1-D list into the empty row list and hence creating the 2-D list.
Approach-3: List Comprehension for creating 2D array in python
This method combines the concept of loops and lists to dynamically create a 2D array.
Here in the example,we create a 3×3 2d array by using list comprehension and initialize it with 1’s.
Code:
#declare rows and cols
rows, cols = (3, 3)
#Create array using list comprehension
arr = [[1 for i in range(cols)] for j in range(rows)]
print(arr)
Output:
[[1, 1, 1], [1, 1, 1], [1, 1, 1]]
Explanation:
- The concept of loop for a list inside a list is applied here and hence creating a 2D list.
Best Approach
- Using method-1 can cause unexpected behaviors while performing element updation
- In this way of creating the 2D array, each row will be referencing the same column. This means, even if we update only one element of the array, it will update the same column in our array.
- The second method is a pretty safe approach but consumes many lines of code.
- The approach-3 stands out as the most efficient approach for initializing an array as we are able to fulfill our purpose with one line of code.Although 2nd approach can be preferred in case of dynamically making a 2d array through input values.
- An important thing to note here is all methods above also showhow to initialize a 2d array in python.
Sample Problems for creating 2d array in Python
Sample Problem – 1
Write a code in python that initializes a 2d array with 0’s.The number of rows and cols must be entered by the user.
Code:
#Take user input for number of rows
rows= int(input("Number of rows:"))
columns = int(input("Number of columns:"))
#Define the matrix
matrix = [[0]*columns]*rows
print(matrix)
Output:
Number of rows:5
Number of columns:4
[[0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0]]
Explanation:
- User Input is taken for number of cols and rows
- Matrix is formed with method discussed in approach-1
- The matrix is initialized with zeros while it is being formed
Sample Problem – 2
Write a code in python that dynamically creates a 2d array through user inputs.The user should input the size and also the array values.
Code:
#Take user input for number of rows
rows= int(input("Number of rows:"))
columns = int(input("Number of columns:"))
#Define the matrix
matrix = [ ]
print("Enter the entries row-wise:")
#for user input
for i in range(rows): # A for loop for row entries
a =[ ]
for j in range(columns): # A for loop for column entries
a.append(int(input()))
matrix.append(a)
print(matrix)
Output:
Number of rows:3
Number of columns:3
Enter the entries row-wise:
123
12
12
[[123, 12, 12]]
Explanation:
- User input is taken for number of rows and cols
- An empty matrix array is defined.
- Iteration for cols of every row appends a new list of values into the matrix array.
- Every matrix cell value is inputted by user
- After iterations are over, a 2d matrix is formed.
Sample Problem – 3
Write a code in python that initializes a 2d array with 1’s.The number of rows and cols must be entered by the user.
Code:
#Take user input for number of rows
rows= int(input("Number of rows:"))
cols = int(input("Number of columns:"))
#Create array using list comprehension
arr = [[1 for i in range(cols)] for j in range(rows)]
print(arr)
Output:
Number of rows:3
Number of columns:3
[[1, 1, 1], [1, 1, 1], [1, 1, 1]]
Explanation:
- User input is taken for number of rows and cols
- A 2d array is created with a method discussed in approach-2(list comprehension method).
- The array created is initialized with one’s.
Conclusion:
2D arrays in Python are a useful data structure for storing and manipulating multidimensional data.Understanding how to use 2D arrays in Python is a valuable skill for data science and scientific computing. 2D arrays provide a flexible and efficient solution for storing and processing the information. With the knowledge gained in this blog, you can now confidently work with 2D arrays in your next Python project.