Pretty print of a 2D list in Python

In this text, we will learn how to get a pretty print of a 2D list in Python. Lists can be one-dimensional, 2-dimensional, and three-dimensional. As a part of this tutorial, we are going to learn what are 2D lists in Python programming. A 2-dimensional list is kind of a nested list, in which each nested list may have elements belonging to a particular class or category. The concept of a 2-dimensional list will be cleared in this tutorial. So, read and understand the text below to learn new coding skills.

2D list:

The 2-dimensional objects or variables come with two types of values arranged in a matrix format containing rows and columns. A 2D list consists of rows and columns. The index of the rows and columns starts from zero and keeps on increasing by one.

Example1:

In this example, we will see a simple 2-dimensional list and understand what a 2D list looks like. The example is given below.

# create a 2D list
same_school= [['John','Henry'],
             ['Jenny','Rylie'],
             ['Addy','George'],
             ['Aum','Bob']]
# print the list
print(same_school)
Output:
[['John', 'Henry'], ['Jenny', 'Rylie'], ['Addy', 'George'], ['Aum', 'Bob']]

Example2:

We can also trace a specific element of a 2D list by just addressing its position in terms of row and column. The example is shown below.

# Create a 2D list
same_school= [['John','Henry'],
             ['Jenny','Rylie'],
             ['Addy','George'],
             ['Aum','Bob']]
# trace Bob in the 2D list
print(same_school[3][1])
Output:
Bob

In this example, we traced the element ‘Bob’ present in the 3rd index row and 2nd index column.

Pretty print of a 2D list in Python using for loop:

We can pretty print the 2D list using a for loop in Python. The for loop can be used as follows.

list of students in a same school
same_school= [['John','Henry'],
             ['Jenny','Rylie'],
             ['Addy','George'],
             ['Aum','Bob']]
# Use of for loop
for rows in same_school:
    print(rows)
Output:
['John', 'Henry']
['Jenny', 'Rylie']
['Addy', 'George']
['Aum', 'Bob']

Pretty print of columns:

We can also get a pretty print of all the elements of the columns using the nested for loop.

same_school= [['John','Henry'],
             ['Jenny','Rylie'],
             ['Addy','George'],
             ['Aum','Bob']]
# Use of for loop
for rows in same_school:
    for cols in rows:
        print(cols)
Output:
John
Henry
Jenny
Rylie
Addy
George
Aum
Bob

Leave a Reply

Your email address will not be published. Required fields are marked *