Skip to content

Instantly share code, notes, and snippets.

@mibmo
Last active February 23, 2024 06:52
Show Gist options
  • Save mibmo/dc66092a43888a8620f312be477e2261 to your computer and use it in GitHub Desktop.
Save mibmo/dc66092a43888a8620f312be477e2261 to your computer and use it in GitHub Desktop.
Print a Python table (list of lists)
def print_table(table, *fields, padding=2):
'''Pretty prints a table (iterable of iterables) with given header fields'''
data = [fields] + table
column_width = max(len(str(column)) for row in data for column in row) + padding
[print("".join(str(column).ljust(column_width) for column in row)) for row in data]
table = [
("Ada", "Lovelace", 36),
("Bjarne", "Stroustrup", 73),
("Ken", "Thomson", 81),
("Linus", "Torvalds", 54),
("Radia", "Perlman", 72),
]
print_table(table, "First name", "Last name", "Age")
'''
output:
First name Last name Age
Ada Lovelace 36
Bjarne Stroustrup 73
Ken Thomson 81
Linus Torvalds 54
Radia Perlman 72
'''
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment