How to print lists as tabular data with Python?

Estimated read time 2 min read

To print lists as tabular data in Python, you can use the tabulate library. The tabulate library provides a simple way to format tabular data and supports various table styles.

Here’s an example of how you can use the tabulate library to print a list as tabular data:

from tabulate import tabulate

data = [
    ["Name", "Age", "Country"],
    ["John", 28, "USA"],
    ["Alice", 32, "Canada"],
    ["Bob", 45, "UK"],
]

# Print the list as a table with the "grid" table style
table = tabulate(data, headers="firstrow", tablefmt="grid")
print(table)

Output:

+-------+-----+---------+
| Name  | Age | Country |
+=======+=====+=========+
| John  | 28  | USA     |
+-------+-----+---------+
| Alice | 32  | Canada  |
+-------+-----+---------+
| Bob   | 45  | UK      |
+-------+-----+---------+

In the example above, we have a 2D list called data representing the tabular data. The first element of the list contains the headers, and the remaining elements represent the rows of the table. We use the tabulate function to format the data, specifying “firstrow” for the headers parameter to indicate that the first row contains the column headers. The tablefmt parameter is set to “grid” to use a grid-style table.

You can customize the table appearance by using different table styles provided by the tabulate library. Some of the available table styles include “plain”, “simple”, “github”, “fancy_grid”, and more. You can experiment with different styles by changing the tablefmt parameter value.

Make sure you have the tabulate library installed before running the code. You can install it using pip:

pip install tabulate

Note: The tabulate library is not part of the Python standard library, so you need to install it separately.

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply