← Back to all snippets
PYTHON

Transpose Data using Python's `zip`

Learn how to transpose rows and columns of data, represented as a list of lists, using the versatile `zip` function in Python for matrix-like operations.

matrix = [
    [1, 2, 3],
    [4, 5, 6],
    [7, 8, 9]
]

# Transpose the matrix
transposed_matrix = [list(row) for row in zip(*matrix)]

print("Original Matrix:")
for row in matrix:
    print(row)

print("
Transposed Matrix:")
for row in transposed_matrix:
    print(row)

# Example with different data types
students_data = [
    ["Alice", 25, "Math"],
    ["Bob", 22, "Physics"],
    ["Charlie", 23, "Chemistry"]
]

# Transpose to get columns as lists
names, ages, subjects = zip(*students_data)
print(f"
Names: {list(names)}")
print(f"Ages: {list(ages)}")
print(f"Subjects: {list(subjects)}")
How it works: This snippet demonstrates how to transpose a "matrix" (a list of lists) using Python's built-in `zip` function combined with the `*` (unpacking) operator. `zip(*matrix)` effectively "unpacks" the inner lists as separate arguments to `zip`, which then groups corresponding elements together. The result is an iterator of tuples, which is then converted back into a list of lists using a list comprehension, or into separate lists if assigning to multiple variables. This is highly useful for operations requiring column-wise access or reorganizing tabular data.

Need help integrating this into your project?

Our team of expert developers can help you build your custom application from scratch.

Hire DigitalCodeLabs