| by Arround The Web | No comments

Initialize 2D List in Python

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:

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.

Example

First, initialize the list row and columns:

col, row = (3, 3)

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:

init_list = [[ 1 for x in range(col)] for y in range (row)]

Next, print the recently initialized 2d list by utilizing the “print()” function:

print(init_list)

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.

Example

At first, import the “numpy” library:

import numpy

Now, initialize the variables:

col = 3

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:

init_2dList = numpy.full((col,row), 1).tolist()

Finally, print the initialized 2d list:

print(init_2dList)

Output

We have explained the different ways to initialize the 2d list in Python.

Conclusion

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.

Share Button

Source: linuxhint.com

Leave a Reply