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

python 2d

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.