Zip Star Transposes Rows Into Columns

zip(*rows) unpacks a list of rows so every column becomes one tuple: transpose tables, align headers with values, then zip(*columns) reverses it.

PythonData Integrity

Code

pythonsnippet
20 lines
rows = [
    ("order", "qty", "price"),
    (1001, 2, 9.5),
    (1002, 1, 24.0),
    (1003, 5, 3.75),
]

# zip(*rows) 先把行列表解包成参数:第 i 列聚成第 i 个元组(转置 transpose)
columns = list(zip(*rows))
print("columns:", columns)

# 表头与各数据列对齐,直接得到字段到取值的映射
header, *body = rows
for column in zip(header, *body):
    name, *values = column
    print(name, "->", values)

# 再解包一次列元组:转回原来的行(rows)
restored = list(zip(*columns))
print("restored:", restored)

Output

Captured from a sandboxed run of this snippet in the build pipeline.

columns: [('order', 1001, 1002, 1003), ('qty', 2, 1, 5), ('price', 9.5, 24.0, 3.75)]
order -> [1001, 1002, 1003]
qty -> [2, 1, 5]
price -> [9.5, 24.0, 3.75]
restored: [('order', 'qty', 'price'), (1001, 2, 9.5), (1002, 1, 24.0), (1003, 5, 3.75)]

Inside the snippet

The one repetition in this snippet is the loop for column in zip(header, *body).

Module-level bindings hold the data — rows, columns, restored — with no function scope in between.

Using it

The demo output is labeled (columns:, restored:), so every printed line maps back to its originating operation.

Key statements

for column in zip(header, *body):
    name, *values = column
    print(name, "->", values)

Interactive Tools for This Topic

FAQ

Does this work in a bare project with no dependencies file?
Yes — a bare project runs it as-is, since nothing needs declaring. Its state lives in module-level bindings: `rows`, `columns`, `restored`.