Print a table in python

It is always a good idea to nicely format the output of your program to make it easier to understand and interpret. Following this principle, Python lists can be displayed in the form of a table.

svg viewer

There are some light and useful Python packages for tabulating output lists. A few of these packages are:

1. tabulate

The tabulate package is the most widely used Python package for tabulating lists; it has many options for specifying headers and table format.

from tabulate import tabulate
l = [["Hassan", 21, "LUMS"], ["Ali", 22, "FAST"], ["Ahmed", 23, "UET"]]
table = tabulate(l, headers=['Name', 'Age', 'University'], tablefmt='orgtbl')
print(table)

2. PrettyTable

PrettyTable is a package that serves a similar purpose to the tabulate package. PrettyTable also has the option to read data from CSV, HTML, or a database.

from prettytable import PrettyTable
l = [["Hassan", 21, "LUMS"], ["Ali", 22, "FAST"], ["Ahmed", 23, "UET"]]
table = PrettyTable(['Name', 'Age', 'University'])
for rec in l:
table.add_row(rec)
print(table)

3. texttable

texttable is another package that serves a similar purpose to the two packages discussed above. With texttable, you can control horizontal/vertical-align, border style, and data types.

from texttable import Texttable
# texttable takes the first reocrd in the list as the column names
# of the table
l = [["Name", "Age", "University"], ["Hassan", 21, "LUMS"], ["Ali", 22, "FAST"], ["Ahmed", 23, "UET"]]
table = Texttable()
table.add_rows(l)
print(table.draw())

Free Resources

Copyright ©2025 Educative, Inc. All rights reserved