Print 2D List in Python (2 Examples)
Hi! This short tutorial will show you how to print 2D lists in the Python programming language.
Here is an overview:
Let’s dive into the Python code!
Create Example 2D List
So, in your preferred Python programming IDE, run the code below to create the 2D list of integer values:
my_list = [[1, 2, 3], [4, 5, 6], [7, 8, 9]] print(my_list) # [[1, 2, 3], [4, 5, 6], [7, 8, 9]] print(type(my_list)) # <class 'list'>
With the example 2D list of integers created, we will now examine 2 ways to print the 2D list.
Example 1: Print 2D List Using Nested for Loop
In this first example, we will use a nested for loop to print the 2D list:
for row in my_list: for element in row: print(element, end=" ") print() # 1 2 3 # 4 5 6 # 7 8 9
This method uses an outer loop that iterates over each row of the list and an inner loop that iterates over each element in the current row. The print() function is then used to display each element.
end argument is set to a space so that the next element is printed on the same line. Finally, the print function is called again, without any arguments, to move to the next line.
Example 2: Print 2D List Using List Comprehension
In this example, we will use list comprehension method to print the 2D list:
[print(row) for row in my_list].pop() # [1, 2, 3] # [4, 5, 6] # [7, 8, 9]
As seen, this code is a more compact way to print each row of a 2D list in Python. The list comprehension iterates over each row in the 2D list and calls the print function to output the row to the console.
The list comprehension generates a list of
None values in the end, which are the return values of the print function. The .pop() method is called to remove the last element, which is
[None, None, None], from the list.
So, with that, we have demonstrated in this tutorial how to print a 2D list in Python. I do hope you found this tutorial helpful! Your use case will determine which solution to adopt.
Video, Further Resources & Summary
Do you need more explanations on how to print 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 print 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:
- Difference Between List & Tuple in Python
- What is List Node in Python? (2 Examples)
- Convert List of Tuples to List of Lists in Python (3 Examples)
- Learn Python Programming
- count() Method for Lists in Python? (2 Examples)
This post has shown how to print 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.