How to Transpose List of Lists in Python Quickly and Easily
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.
transposed = list(zip(*original_list))
Example
This example shows how to transpose a 3x3 list of lists. The rows become columns after transposing.
original_list = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
]
transposed = list(zip(*original_list))
print(transposed)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.
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]]
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.