Pages

Topics

Tools

↑↓navigate↵openescclose
All guides

Python PrettyTable: Create, Format, and Sort Tables

Use Python PrettyTable to turn lists into readable terminal tables: install, add rows, align columns, sort data, and apply built-in styles.

~3 min readPython
#PrettyTable#Table Formatting#CLI Output#Data Presentation
A clean terminal window showing a formatted table with aligned columns and a highlighted sort arrow, representing Python PrettyTable's output.

When you need to display tabular data in a terminal or log file, Python's prettytable library turns plain lists into readable, aligned tables. This article covers the core API for creating tables, adding rows, formatting columns, sorting rows, and applying built-in styles.

Installing and Importing PrettyTable

prettytable is a third-party package, so install it with pip:

bash
pip install prettytable

Then import the PrettyTable class in your script:

python
from prettytable import PrettyTable

Creating a Table and Adding Rows

Instantiate a PrettyTable object and define column names. Rows are added with add_row, which expects a list of values in the same order as the columns.

python
table = PrettyTable() table.field_names = ['Name', 'Role', 'Years'] table.add_row(['Alice', 'Engineer', 5]) table.add_row(['Bob', 'Manager', 8]) table.add_row(['Carol', 'Designer', 3])

print(table) renders a formatted ASCII table with borders and headers. The field_names attribute defines the header row and the number of columns. Every add_row call must supply the same number of values; otherwise, prettytable raises a ValueError.

Formatting Columns and Alignment

Use the align attribute to control the alignment of a column. It accepts 'l', 'c', or 'r' for left, center, and right.

python
table.align['Name'] = 'c' table.align['Role'] = 'l' table.align['Years'] = 'r'

Column widths are computed automatically from the longest cell. You can set a minimum width with min_width:

python
table.min_width['Name'] = 10

For compact output, max_width limits the rendered width of a column:

python
table.max_width['Name'] = 12

Sorting Rows by a Column

Use sortby to choose the column used for sorting, and reversesort to switch between ascending and descending order:

python
table.sortby = 'Years' table.reversesort = True

This sorts by the Years column in descending order. For multi-column sorting, sortby can also be a tuple of field names; the order determines priority:

python
table.sortby = ('Role', 'Name')

PrettyTable compares the stored values in the selected columns by default. To use a custom key, set sort_key to a function that receives a row and returns the sort value. For example, to sort a string-based numeric column numerically:

python
years_idx = table.field_names.index('Years') table.sortby = 'Years' table.sort_key = lambda row: int(row[years_idx])

Sorting is stable, so rows with equal keys retain their original relative order.

Customizing Table Style and Borders

prettytable provides several built-in styles via set_style. For example, Style.MARKDOWN produces Markdown-compatible tables, and Style.PLAIN_COLUMNS removes all borders.

python
from prettytable import Style table.set_style(Style.MARKDOWN) print(table)

You can also control individual border characters by modifying table.horizontal_char, table.vertical_char, and table.junction_char. This is useful when you need to match a specific output format or embed the table in a plain-text document.

Handling Large Data and Performance

prettytable stores every row in memory, so it is not suitable for streaming millions of records. add_rows accepts any iterable of rows, including generators, which is convenient for building a table programmatically, but it does not reduce memory use because the table still holds all of the rows.

python
table = PrettyTable() table.field_names = ['n', 'n_squared'] table.add_rows([i, i**2] for i in range(1000))

For very large output, generate plain text directly instead of holding every row in a PrettyTable.

Sorting is O(n log n) and happens when the table is rendered, not when you assign sortby. If you render the same table repeatedly and do not need PrettyTable's sorting, sort the row data before adding it so the table stays in the order you want.

Common Pitfalls and Compatibility Notes

One frequent mistake is mixing types in a column. PrettyTable converts values to strings for display, but sorting compares the stored values in the selected column. If a column contains both strings and numbers, sorting can raise TypeError in Python 3 because the two types cannot be compared. Convert values to a consistent type before adding rows, or provide a sort_key that returns a consistent type.

Set field_names before adding rows. If you need to add a new column after rows exist, use add_column or create a new table structure. For concurrent writes, prettytable is not thread-safe; if multiple threads write to the same table instance, protect modifications with a lock or build separate tables per thread and add their rows to a final table afterward.

Try matching browser tools

All tools

Small utilities that fit Python work — they run entirely in this browser tab, so nothing you paste leaves your device.

All Python guides

More in Python

All Python guides

The guides filed next to this one in Python, in library order.