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.
There are some light and useful Python packages for tabulating output lists. A few of these packages are:
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 tabulatel = [["Hassan", 21, "LUMS"], ["Ali", 22, "FAST"], ["Ahmed", 23, "UET"]]table = tabulate(l, headers=['Name', 'Age', 'University'], tablefmt='orgtbl')print(table)
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 PrettyTablel = [["Hassan", 21, "LUMS"], ["Ali", 22, "FAST"], ["Ahmed", 23, "UET"]]table = PrettyTable(['Name', 'Age', 'University'])for rec in l:table.add_row(rec)print(table)
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 tablel = [["Name", "Age", "University"], ["Hassan", 21, "LUMS"], ["Ali", 22, "FAST"], ["Ahmed", 23, "UET"]]table = Texttable()table.add_rows(l)print(table.draw())
Free Resources