ID : 328
viewed : 76
Tags : PythonPython List
98
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.
append()
MethodThis 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]]
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]]
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]]
itertools.repeat
MethodThe 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]]
numpy.full()
MethodThis 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]]