Creating a table in Python involves structuring data into rows and columns for clear
representation. Tables can be displayed in various formats, including plain text, grids or
structured layouts. Python provides multiple ways to generate tables, depending on the
complexity and data size.
Using Tabulate
Tabulate module is the most efficient way to create tables. It offers various formatting styles,
requires minimal code and automatically aligns data properly. This method is ideal for small
to medium datasets where quick visualization is needed.
from tabulate import tabulate
# assign data
a=[
["Nikhil", "Delhi"],
["Ravi", "Kanpur"],
["Manish", "Ahmedabad"],
["Prince", "Bangalore"]
# create header
headers = ["Name", "City"]
print(tabulate(a, headers=headers, tablefmt="grid"))
Output:
Explanation: tabulate() function is called with three arguments: the data list, headers and
tablefmt="grid", which specifies the grid-style formatting for better readability.
What is a Two-Dimensional Table?
A two-dimensional table is like a matrix or grid — it has rows and columns.
In Python, we can represent it using lists of lists.
Example structure:
Here:
table[0] → [1, 2, 3] (first row)
table[1][2] → 6 (second row, third column)
Example 1: Creating and Printing a 2D Table
Output:
Example 2: Pretty Display of a 2D Table
Output: