Printing Lists as Tabular Data in Python
Last Updated :
20 Apr, 2025
The goal here is to present lists in a more structured, readable format by printing them as tables. Instead of displaying raw list data, formatting it into tabular form with rows and columns makes it easier to understand and analyze. For example, given a list like [['Name', 'Age'], ['Aditi', 19], ['Anmol', 16]], we want to display it as a clean table with headers and values neatly aligned. Let’s explore different methods to do this.
Using pandas
Pandas is the most widely used library for handling and presenting data in tabular form. It provides the DataFrame structure, which allows for efficient data manipulation, analysis and visualization. With just a few lines of code, it can present complex data in a clear tabular format.
Python
import pandas as pd
a = [['Apple', 25], ['Banana', 20]]
df = pd.DataFrame(a, columns=['Fruit', 'Price/Kg'])
print(df)
Output
Using pandasExplanation: Each sublist in a represents a row of data. pd.DataFrame() converts it into a structured table with column labels 'Fruit' and 'Price/Kg', and print(df) displays it in a readable tabular format.
Using tabulate library
tabulate library is known for its ability to format tables with different styles and outputs (e.g., plain text, HTML, LaTeX). It is a powerful yet lightweight solution for printing data in tabular form.
Python
from tabulate import tabulate
a = [['Aditi', 19], ['Anmol', 16], ['Bhavya', 19]] # data
b = ['Name', 'Age'] # headers
print(tabulate(a, headers=b))
Output
Using tabulateExplanation: Each sublist represents a row of data, while the list b provides the column headers 'Name' and 'Age'. The tabulate() function combines them and prints a well-structured, easy-to-read table output.
Using PrettyTable library
PrettyTable is a Python library designed to print ASCII tables in a visually pleasing manner. It offers many customization options for table alignment, formatting and column adjustments.
Python
from prettytable import PrettyTable
t = PrettyTable(['Name', 'Age'])
t.add_row(['Aditi', 19])
t.add_row(['Anmol', 16])
t.add_row(['Bhavya', 19])
print(t)
Output
using PrettyTableExplanation: It initializes the table with column headers 'Name' and 'Age', then adds each data entry as a row using add_row().
Using Texttable library
texttable module is ideal for generating ASCII-style tables with minimal configuration. It supports the creation of both fixed-size and dynamic tables and is very efficient for quick text-based output.
Python
from texttable import Texttable
t = Texttable()
t.add_rows([['Name', 'Age'], ['Aditi', 19], ['Anmol', 16],['Bhavya',19]])
print(t.draw())
Output
Using TexttableExplanation: It creates a table object t, adds multiple rows using add_rows() with the first row as column headers 'Name' and 'Age' and then prints the table using draw(), which returns a neatly bordered ASCII-style table.