How to Print a List in Tabular Format Using Python?

Estimated read time 1 min read

To print a list in a tabular format using Python, you can use the tabulate module. Here’s an example:

from tabulate import tabulate

my_list = [["Alice", 25, "New York"],
           ["Bob", 30, "San Francisco"],
           ["Charlie", 35, "London"]]

headers = ["Name", "Age", "City"]

print(tabulate(my_list, headers=headers))

In this example, we define a list of lists my_list that contains some data. We also define a list headers that contains the column headers. We then use the tabulate function from the tabulate module to format and print the list in a tabular format.

The tabulate function takes two arguments: the list of lists to be formatted (in this case my_list), and the list of column headers (in this case headers). The function returns a formatted string that represents the list in a tabular format.

The output of the above code will be:

Name       Age  City
--------  ----  --------------
Alice      25    New York
Bob        30    San Francisco
Charlie    35    London

Note that you need to install the tabulate module before you can use it. You can install it using pip by running pip install tabulate.

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply