Introduction

In Python, there are multiple ways in which a user can create 2d arrays or lists. But before implementing these ways we need to understand the differences between these ways because it can create complications that can turn out to be hard to trace.

Initializing 1D Array

Let us see some common ways of initializing a 1D array with 0s filled.

Code

size = 4
arr = [0]*size
print(arr)

Output

[0, 0, 0, 0]

Let us create a list using list comprehension.

Code

size = 4
arr = [i for i in range(size)]
print(arr)

Output

[0, 1, 2, 3]

write your code here: Coding Playground

Creating a 2D array

Method 1: Naive approach

Code

r, c = (5, 5)
arr = [[0]*c]*r
print(arr)

Output

[[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]]

Explanation

In the code above, we multiply the array with the columns ©, now this will result in a 1D list, whose size will be equal to the number of columns. After it, we again multiply the array with the rows ®, again this will result in the construction of a 2D list.

Now sometimes we need to be careful while using this method as it can cause unexpected behaviours. Each row in this 2D array will reference the same column. This means if we try to update only a single element of the array, it will update the same column in our array.

Code

r, c = (5, 5)
arr = [[0]*c]*r
print(arr, "before update")

arr[0][0] = 1 # updating only one element
print(arr, "after update")

Output

([[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]], 'before update')
([[1, 0, 0, 0, 0], [1, 0, 0, 0, 0], [1, 0, 0, 0, 0], [1, 0, 0, 0, 0], [1, 0, 0, 0, 0]], 'after update')

write your code here: Coding Playground

Creating a 2D array using list comprehension

Code

r, c = (5, 5)
arr = [[0 for i in range(c)] for j in range(r)]
print(arr)

Output

[[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]]

write your code here: Coding Playground

Explanation

In the above code, we are using the list comprehension technique, in this technique we use a loop for a list and inside a list, hence creating a 2D list.

Creating a 2D array using empty list

Code

arr=[]
r, c=5,5
for i in range(r):
clm = []
for j in range(c):
clm.append(0)
arr.append(clm)
print(arr)

Output

[[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]]

write your code here: Coding Playground

Explanation

In the code above, we are trying to append zeros as elements for some columns times and after it we are trying to append this 1D list to an empty row list, hence creating a 2D list.