Skip to content

Fix IndexError with maxheadercolwidths on empty tables#393

Closed
bysiber wants to merge 1 commit intoastanin:masterfrom
bysiber:fix-maxheadercolwidths-empty-table
Closed

Fix IndexError with maxheadercolwidths on empty tables#393
bysiber wants to merge 1 commit intoastanin:masterfrom
bysiber:fix-maxheadercolwidths-empty-table

Conversation

@bysiber
Copy link
Contributor

@bysiber bysiber commented Feb 21, 2026

When maxheadercolwidths is passed and the table has no data rows, tabulate() raises an IndexError because it tries to access list_of_lists[0] to determine the column count on an empty list.

>>> tabulate([], headers=["one", "two", "three"], maxheadercolwidths=5)
IndexError: list index out of range

This fix checks whether list_of_lists is empty and falls back to len(headers) for the column count, which is the same pattern already used in the maxcolwidths handling a few lines above.

>>> tabulate([], headers=["one", "two", "three"], maxheadercolwidths=5)
'one    two    three\n-----  -----  -------'

Fixes #365

When maxheadercolwidths is set and the table has no data rows,
list_of_lists[0] raises an IndexError since the list is empty.

Fall back to len(headers) when list_of_lists is empty to determine
the number of columns, matching how maxcolwidths already handles
the same scenario.
@astanin
Copy link
Owner

astanin commented Mar 4, 2026

Thank you for pointing this out. I did a slightly different fix.

@astanin astanin closed this Mar 4, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

IndexError on empty tables when maxheadercolwidths is used

2 participants