From 8ee2ce12a6bd41a1513670c8a37194b5be9f6b2a Mon Sep 17 00:00:00 2001 From: Rajpal14 Date: Tue, 10 Nov 2026 02:15:30 +0530 Subject: [PATCH] Do not drop columns when headers are shorter than ragged rows (#494) When tabular data contains rows of varying lengths (ragged rows) and the first row has fewer columns than subsequent rows, _normalize_tabular_data previously computed headers_pad using only len(rows[0]). When headers was shorter than the maximum row length, the headers list remained shorter than the total number of columns, causing zip(cols, aligns, minwidths) to truncate the table columns. Now headers_pad uses the maximum column count across all non-separating data rows, ensuring all table columns are properly preserved and aligned. Fixes #494 --- tabulate/__init__.py | 3 ++- test/test_regression.py | 8 ++++++++ 2 files changed, 10 insertions(+), 1 deletion(-) diff --git a/tabulate/__init__.py b/tabulate/__init__.py index 12a2950..5093f23 100644 --- a/tabulate/__init__.py +++ b/tabulate/__init__.py @@ -1607,7 +1607,8 @@ def _normalize_tabular_data(tabular_data, headers, showindex="default"): # pad with empty headers for initial columns if necessary headers_pad = 0 if headers and len(rows) > 0: - headers_pad = max(0, len(rows[0]) - len(headers)) + max_row_cols = max(len(r) for r in rows if not _is_separating_line(r)) if rows else 0 + headers_pad = max(0, max_row_cols - len(headers)) headers = [""] * headers_pad + headers return rows, headers, headers_pad diff --git a/test/test_regression.py b/test/test_regression.py index 9555676..94de686 100644 --- a/test/test_regression.py +++ b/test/test_regression.py @@ -420,6 +420,14 @@ def test_ragged_rows(): assert_equal(expected, result) +def test_ragged_rows_with_short_headers(): + "Regression: headers should not drop columns from ragged rows (issue #494)" + table = [["a"], ["b", "KEEP"]] + expected = "\n".join([" tail", "-- ------", "a", "b KEEP"]) + result = tabulate(table, headers=["tail"]) + assert_equal(expected, result) + + def test_empty_pipe_table_with_columns(): "Regression: allow empty pipe tables with columns, like empty dataframes (github issue #15)" table = []