This question already has an answer here:
- Transpose list of lists 10 answers
Let's say I have a SINGLE list [[1,2,3],[4,5,6]]
How do I transpose them so they will be: [[1, 4], [2, 5], [3, 6]]
?
Do I have to use the zip
function? Is the zip
function the easiest way?
def m_transpose(m):
trans = zip(m)
return trans
zip()
doesn't seem to do what you wanted, usingzip()
you get alist
oftuples
. This should work though:You can use map with
None
as the first parameter:Unlike
zip
it works on uneven lists:Then call map again with
list
as the first parameter if you want the sub elements to be lists instead of tuples:(Note: the use of map with
None
to transpose a matrix is not supported in Python 3.x. Use zip_longest from itertools to get the same functionality...)Using
zip
and*splat
is the easiest way in pure Python.Note that you get tuples inside instead of lists. If you need the lists, use
map(list, zip(*l))
.If you're open to using
numpy
instead of a list of lists, then using the.T
attribute is even easier:The exact way of use
zip()
and get what you want is:This code use
list
keyword for casting thetuples
returned byzip
intolists
.