Like other programming languages, Python also has different data structures, and the list is one of them. The list stores several values linearly and exists in two-dimensional data. Additionally, a multi-dimensional data structure is required to keep such data. In Python, a list contains different types of elements that can be initialized by utilizing different built-in methods.
This write-up will discuss the ways of initializing the 2d list in Python.
How to Initialize 2D List in Python?
To initialize a two-dimensional list in Python, the below-stated methods are used:
- range() method
- numpy.full() method
Method 1: Initialize 2D List Using “range()” Method in Python
“range()” is the built-in function in Python that is used for initializing a two-dimensional list. This method returns a sequence of numbers starting from the zeros, then incremented by “1” by default. It stops before the specified number.
First, initialize the list row and columns:
Then, use the “for” loop technique to initialize the 2d list. Call the “range()” method that takes only an integer value and returns a traversal object, and passes them to the “init_list” variable:
Next, print the recently initialized 2d list by utilizing the “print()” function:
It can be seen in the below-provided output, the specified 2d list has been initialized successfully with “1”:
Method 2: Initialize 2D List Using “numpy.full()” Method in Python
Another way to initialize the 2d list in Python is by utilizing the “numpy.full()” function. It will create an array, and the “tolist()” function is used along with it to alter a created 2d array into a list.
At first, import the “numpy” library:
Now, initialize the variables:
row = 3
Call the “numpy.full()” function by passing the previously initialized variables as an argument along with the “tolist()” function and passes them to the “init_2dlist” variable:
Finally, print the initialized 2d list:
We have explained the different ways to initialize the 2d list in Python.
To initialize a 2d list in Python, the “range()” method and “numpy.full()” method with the “tolist()” method are utilized. The “range()” returns the sequence of numbers that started from “0” and incremented with “1” by default. The “numpy.full()” method returns an array, and the “tolist” function changes the array into a 2d list. This write-up described the ways of initializing the 2d list in Python.