Welcome, guest | Sign In | My Account | Store | Cart

A short way to turn rows into columns. Not necessarily the fastest, mind you. The list comprehension is your friend.

Python, 7 lines
arr = [[1,2,3],[4,5,6],[7,8,9],[10,11,12]]

# The subject should be regular, with all rows the same length

print [[r[col] for r in arr] for col in range(len(arr[0]))]

[[1, 4, 7, 10], [2, 5, 8, 11], [3, 6, 9, 12]]

Sometimes data just comes at you the wrong way. For instance, if you use Microsoft's ADO database interface, due to array element ordering differences betwen Python and Microsoft's implementation language, the GetRows() method actually appears to return database columns in Python, despite its name. This solution was chosen to demonstrate nested list comprehensions. Notice that the inner comprehension varies what is selected from (the row) rather than the selector (the column), which is varied in the outer comprehension. This achieves the required transposition.


Raymond Hettinger 22 years, 1 month ago  # | flag

Shorter and Faster.

print zip(*arr)
Attila Vásárhelyi 21 years, 6 months ago  # | flag

Not the same! While the original proposal returns a list of lists, zip(*arr) returns a list of tuples, and as a consequence the elements of the array cannot be modifed anymore.

Chris Perkins 20 years, 10 months ago  # | flag

OK then... map(list, zip(*arr))

Created by Steve Holden on Thu, 11 Oct 2001 (PSF)
Python recipes (4591)
Steve Holden's recipes (3)

Required Modules

  • (none specified)

Other Information and Tasks