From 681bd511ac348edfc6ac30f7cd8c8849b659f807 Mon Sep 17 00:00:00 2001 From: Kadir Can Ozden <101993364+bysiber@users.noreply.github.com> Date: Sun, 22 Feb 2026 00:29:04 +0300 Subject: [PATCH] Fix IndexError with maxheadercolwidths on empty tables 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. --- tabulate/__init__.py | 28 +++++++++++++++++----------- 1 file changed, 17 insertions(+), 11 deletions(-) diff --git a/tabulate/__init__.py b/tabulate/__init__.py index e100c09..957ba9b 100644 --- a/tabulate/__init__.py +++ b/tabulate/__init__.py @@ -2262,18 +2262,24 @@ def tabulate( ) if maxheadercolwidths is not None: - num_cols = len(list_of_lists[0]) - if isinstance(maxheadercolwidths, int): # Expand scalar for all columns - maxheadercolwidths = _expand_iterable( - maxheadercolwidths, num_cols, maxheadercolwidths - ) - else: # Ignore col width for any 'trailing' columns - maxheadercolwidths = _expand_iterable(maxheadercolwidths, num_cols, None) + 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: + if isinstance(maxheadercolwidths, int): # Expand scalar for all columns + maxheadercolwidths = _expand_iterable( + maxheadercolwidths, num_cols, maxheadercolwidths + ) + else: # Ignore col width for any 'trailing' columns + maxheadercolwidths = _expand_iterable(maxheadercolwidths, num_cols, None) - numparses = _expand_numparse(disable_numparse, num_cols) - headers = _wrap_text_to_colwidths( - [headers], maxheadercolwidths, numparses=numparses, break_long_words=break_long_words, break_on_hyphens=break_on_hyphens - )[0] + numparses = _expand_numparse(disable_numparse, num_cols) + headers = _wrap_text_to_colwidths( + [headers], maxheadercolwidths, numparses=numparses, break_long_words=break_long_words, break_on_hyphens=break_on_hyphens + )[0] # empty values in the first column of RST tables should be escaped (issue #82) # "" should be escaped as "\\ " or ".."