Skip to content

fix: handle empty tables when maxheadercolwidths is set#395

Open
Jo2234 wants to merge 1 commit intoastanin:masterfrom
Jo2234:fix/empty-table-maxheadercolwidths
Open

fix: handle empty tables when maxheadercolwidths is set#395
Jo2234 wants to merge 1 commit intoastanin:masterfrom
Jo2234:fix/empty-table-maxheadercolwidths

Conversation

@Jo2234
Copy link

@Jo2234 Jo2234 commented Mar 1, 2026

Summary

Fix IndexError when tabulate() is called with an empty table and maxheadercolwidths is not None.

Problem

from tabulate import tabulate
tabulate([], headers=['Name', 'Age'], maxheadercolwidths=10)
# IndexError: list index out of range

The crash occurs at:

if maxheadercolwidths is not None:
    num_cols = len(list_of_lists[0])  # IndexError when list_of_lists is empty

Fix

 if maxheadercolwidths is not None:
-    num_cols = len(list_of_lists[0])
+    if len(list_of_lists):
+        num_cols = len(list_of_lists[0])
+    elif len(headers):
+        num_cols = len(headers)
+    else:
+        num_cols = 0
+    if num_cols:
         ...  # existing width wrapping logic

This mirrors the approach already used for maxcolwidths (lines 2250-2253) which correctly handles empty tables.

Fixes #365

When tabulate() is called with an empty table and maxheadercolwidths
is not None, an IndexError is raised at:
    num_cols = len(list_of_lists[0])
because list_of_lists is an empty list.

This fix:
- Falls back to len(headers) when list_of_lists is empty
- Skips header width wrapping entirely when num_cols is 0
  (no columns to wrap)

Fixes astanin#365
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

1 participant