How to Initialize a 2D Array in Python

  1. Initialize 2D Array in Python Using the append() Method
  2. Initialize 2D Array in Python Using the loop Method
  3. Initialize 2D Array in Python Using the List Comprehension Method
  4. Initialize 2D Array in Python Using the itertools.repeat Method
  5. Initialize 2D Array in Python Using the numpy.full() Method

A Python list is mutable, and it can be created, deleted, or modified. It can hold different data types in an ordered manner. List values can be initialized with 0 or any other value in several ways.

This article will demonstrate different methods to initialize a 2D list in Python.

Initialize 2D Array in Python Using the append() Method

This method adds one list to another List and initializes with the specified values in the list.

The complete example code is as follows:

list1 = [0,0] 
list2 = [0,0] 
list1.append(list2)
print(list1)

Output:

[0, 0, [0, 0]]

Initialize 2D Array in Python Using the loop Method

This method uses the loop method to initialize the Python list. At the start, we define the dimensions of the list and then initialize it. The range() function takes an integer as the argument and returns an iterable object.

The complete example code is as follows:

dim1, dim2 = (2, 2) 
output = [[0 for i in range(dim1)] for j in range(dim2)] 
print(output)

Output:

[[0, 0], [0, 0]]

Initialize 2D Array in Python Using the List Comprehension Method

We can initialize the list to default values by this method. It is the most Pythonic solution for the initialization of the list. This method permits us to make list by using the iterable object like range() function’s object.

The complete example code is as follows:

dim_row = 2
dim_columns = 2

output = [[0 for x in range(dim_columns)] for i in range(dim_row)]

print(output)

Output:

[[0, 0], [0, 0]]

Initialize 2D Array in Python Using the itertools.repeat Method

The itertools is a fast and memory-efficient tool used individually or as a combination with other functions. This method has a repeat() function instead of the range() function used in the List Comprehension method.

The complete example code is as follows:

from itertools import repeat

dim = 2
output = list(repeat([0], dim))

print(output) 

Output:

[[0], [0]]

Initialize 2D Array in Python Using the numpy.full() Method

This method will also initialize the list elements, but it is slower than the list Comprehension method.

The complete example code is as follows:

import numpy

dim_columns = 2
dim_rows = 2

output = numpy.full((dim_columns,dim_rows), 0).tolist()

print(output)

The numpy.full() function of the NumPy will create an array and the tolist() function of NumPy will convert that array to a Python List.

Output:

[[0, 0], [0, 0]]

Related Article - Python List

  • How to Read CSV to List in Python
  • How to Convert a List to String in Python