Create 2D List in Python (2 Examples)
Hi! This short tutorial will demonstrate to you how to make a 2D list in the Python programming language.
Here is a quick overview:
Let’s get right into the Python code!
Example 1: Build 2D List Using Nested For Loop
In this example, we will use a nested for loop to make a 2D list of 0 integers. Run the code below in your favored Python IDE:
rows = 3 cols = 3 my_list =  for i in range(rows): row =  for j in range(cols): row.append(0) my_list.append(row) print(my_list) # [[0, 0, 0], [0, 0, 0], [0, 0, 0]] print(type(my_list)) # <class 'list'>
In the example above, we, first of all, initialized the number of rows and columns for the 2D list. The first loop created the rows, which correspond to the number of rows initialized using the range() function.
The second loop created the columns, corresponding to the initialized number of columns, and then appended, with 0 integer values, to the rows using the append() method. The rows are then returned as appended to the 2D list called “my_list”.
Example 2: Build 2D List Using List Comprehension
In this example, we will use the list comprehension method to generate a 2D list of 0s:
rows = 3 cols = 3 my_list = [[0 for j in range(cols)] for i in range(rows)] print(my_list) # [[0, 0, 0], [0, 0, 0], [0, 0, 0]] print(type(my_list)) # <class 'list'>
Much like in the nested for loop example, we also initialized the 3 rows and 3 columns for the 2D list in this example. Then, using the list comprehension method, we ran 2 iterations that created the rows and columns in the number of initialized rows and columns and then populated the columns with the 0 integer value.
The final output was then stored inside the 2D list called “my_list”. With that, we have demonstrated, by examples, how to create a 2D list in Python. I do hope you found this tutorial helpful!
Video, Further Resources & Summary
Do you need more explanations on how to create a 2D list in Python? Then you should have a look at the following YouTube video of the Statistics Globe YouTube channel.
In the video, we explain in some more detail how to create a 2D list in Python.
The YouTube video will be added soon.
Furthermore, I encourage you to check out other interesting Python list tutorials on Statistics Globe, starting with these ones:
- Add Float to Each Element in List in Python (4 Examples)
- Difference between List & pandas DataFrame in Python
- count() Method for Lists in Python (2 Examples)
- Learn Python Programming
- Convert List of Tuples to List of Lists in Python (3 Examples)
This post has shown how to create a 2D list in Python. In case you have further questions, you may leave a comment below.
This page was created in collaboration with Ifeanyi Idiaye. You might check out Ifeanyi’s personal author page to read more about his academic background and the other articles he has written for the Statistics Globe website.
Statistics Globe Newsletter