How do I transpose a List?

12,739

Solution 1

Using zip and *splat is the easiest way in pure Python.

>>> list_ = [[1,2,3],[4,5,6]]
>>> zip(*list_)
[(1, 4), (2, 5), (3, 6)]

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:

>>> import numpy as np
>>> a = np.array([[1,2,3],[4,5,6]])
>>> print(*a)
[1 2 3] [4 5 6]
>>> print(*a.T)
[1 4] [2 5] [3 6]

Solution 2

You can use map with None as the first parameter:

>>> li=[[1,2,3],[4,5,6]]
>>> map(None, *li)
[(1, 4), (2, 5), (3, 6)]

Unlike zip it works on uneven lists:

>>> li=[[1,2,3],[4,5,6,7]]
>>> map(None, *li)
[(1, 4), (2, 5), (3, 6), (None, 7)]
>>> zip(*li)
[(1, 4), (2, 5), (3, 6)]
#                      ^^ 7 missing...

Then call map again with list as the first parameter if you want the sub elements to be lists instead of tuples:

>>> map(list, map(None, *li))
[[1, 4], [2, 5], [3, 6]]

(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...)

Solution 3

The exact way of use zip() and get what you want is:

>>> l = [[1,2,3],[4,5,6]]
>>> [list(x) for x in zip(*l)]
>>> [[1, 4], [2, 5], [3, 6]]

This code use list keyword for casting the tuples returned by zip into lists.

Share:
12,739
user2581724
Author by

user2581724

Updated on June 22, 2022

Comments

  • user2581724
    user2581724 almost 2 years

    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