6

How to initialize a 2D List in Python?

 2 years ago
source link: https://www.pythoncentral.io/how-to-initialize-a-2d-list-in-python/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

How to initialize a 2D List in Python?

This article is part of in the series
Published: Friday 17th September 2021
Last Updated: Friday 24th September 2021

The list is a data structure that is used to store multiple values linearly. However, there exist two-dimensional data. A multi-dimensional data structure is needed to keep such type of data.

In Python, a two-dimensional list is an important data structure. It is essential to learn the working of Python 1D list efficiently to work with Python 2D list. We call Python 2D list as nested list as well as list of list.

In the following article, we will learn how to work with Python 2D list. There will be examples for better learning.

You can visit Codeleaks.io for Python detailed tutorials with examples.

Python 1D list vs. 2D list

The one-dimensional list of Python lists looks as follows:

List= [ 2, 4, 8, 6 ]

On the other hand, the Python 2D list looks like this:

List= [ [ 2, 4, 6, 8 ], [ 12, 14, 16, 18 ], [ 20, 40, 60, 80 ] ]

How to initialize Python 2D list?

Python offers various techniques for initializing a 2D list in Python. List Comprehension is used to return a list. Python 2D list consists of nested lists as its elements.

Let’s discuss each technique one by one.

Technique No. 01

This technique uses List Comprehension to create Python 2D list. Here we use nested List comprehension to initialize a two-dimensional list.

rows = 3

columns = 4

Python_2D_list = [[5 for j in range(columns)]

for i in range(rows)]

print(Python_2D_list )

Output:

[[5, 5, 5, 5], [5, 5, 5, 5], [5, 5, 5, 5]]

Technique No. 02

rows = 2

columns = 3

Python_2D_list = [[7]*columns]*rows

print(Python_2D_list )

Output:

[[7, 7, 7], [7, 7, 7]]

Technique No. 03

rows = 6

columns = 6

Python_2D=[]

for i in range(rows):

column = []

for j in range(columns):

column.append(3)

Python_2D.append(column)

print(Python_2D)

Output:

[[3, 3, 3, 3, 3, 3], [3, 3, 3, 3, 3, 3], [3, 3, 3, 3, 3, 3], [3, 3, 3, 3, 3, 3], [3, 3, 3, 3, 3, 3], [3, 3, 3, 3, 3, 3]]

Applications of Python 2D list

Now we will list down the applications of the Python 2D list.

  1. Game boards
  2. Tabular data
  3. Matrices in Mathematics
  4. Grids
  5. DOM elements in web development
  6. Scientific experiment data

and many more.

Conclusion

Python 2D list has its limitations and advantages. The use of a Python 2D list depends on the requirement of the Python program. I hope the article helped you learn the concept of Python 2D list.


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK