0
0
PythonHow-ToBeginner · 3 min read

How to Transpose List of Lists in Python Quickly and Easily

To transpose a list of lists in Python, use the zip() function with unpacking operator *. This swaps rows and columns, turning rows into columns and vice versa.
📐

Syntax

The basic syntax to transpose a list of lists is:

transposed = list(zip(*original_list))

Here, original_list is your list of lists. The * operator unpacks the inner lists as separate arguments to zip(). The zip() function pairs elements from each list by their positions, effectively swapping rows and columns. Wrapping with list() converts the result back to a list of tuples.

python
transposed = list(zip(*original_list))
💻

Example

This example shows how to transpose a 3x3 list of lists. The rows become columns after transposing.

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

transposed = list(zip(*original_list))
print(transposed)
Output
[(1, 4, 7), (2, 5, 8), (3, 6, 9)]
⚠️

Common Pitfalls

One common mistake is forgetting to unpack the list with *. Without unpacking, zip() treats the entire list as a single argument, returning the original list wrapped in tuples.

Also, the result of zip() is tuples, not lists. If you need lists, convert each tuple to a list.

python
original_list = [[1, 2], [3, 4]]

# Wrong: missing unpacking
wrong = list(zip(original_list))
print(wrong)  # Output: [([1, 2],), ([3, 4],)]

# Right: with unpacking
right = list(zip(*original_list))
print(right)  # Output: [(1, 3), (2, 4)]

# Convert tuples to lists if needed
right_lists = [list(t) for t in right]
print(right_lists)  # Output: [[1, 3], [2, 4]]
Output
[([1, 2],), ([3, 4],)] [(1, 3), (2, 4)] [[1, 3], [2, 4]]
📊

Quick Reference

Remember these tips when transposing lists:

  • Use zip(*list_of_lists) to transpose.
  • Unpack the list with * to pass inner lists as separate arguments.
  • Result is tuples; convert to lists if needed.
  • Works best when all inner lists have the same length.

Key Takeaways

Use zip with unpacking operator * to transpose list of lists in Python.
Always unpack the list to avoid incorrect results.
The output of zip is tuples; convert to lists if you need mutable sequences.
Ensure inner lists have equal length for consistent transposition.
Transposing swaps rows and columns effectively.