4
votes

Is there any fast method to make a transposition of a rectangular 2D matrix in Python (non-involving any library import).?

Say, if I have an array

X=[ [1,2,3],
    [4,5,6] ]

I need an array Y which should be a transposed version of X, so

Y=[ [1,4],
    [2,5],
    [3,6] ] 
3
How fast is fast? Do you have a speed requirement? - Xavier Ho

3 Answers

20
votes

Simple: Y=zip(*X)

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

EDIT: to answer questions in the comments about what does zip(*X) mean, here is an example from python manual:

>>> range(3, 6)             # normal call with separate arguments
[3, 4, 5]
>>> args = [3, 6]
>>> range(*args)            # call with arguments unpacked from a list
[3, 4, 5]

So, when X is [[1,2,3], [4,5,6]], zip(*X) is zip([1,2,3], [4,5,6])

6
votes
>>> X = [1,2,3], [4,5,6]]
>>> zip(*X)
[(1,4), (2,5), (3,6)]
>>> [list(tup) for tup in zip(*X)]
[[1,4], [2,5], [3,6]]

If the inner pairs absolutely need to be lists, go with the second.

5
votes

If you're working with matrices, you should almost certainly be using numpy. This will perform numerical operations easier and more efficiently than pure Python code.

>>> x = [[1,2,3], [4,5,6]]
>>> x = numpy.array(x)
>>> x
array([[1, 2, 3],
       [4, 5, 6]])
>>> x.T
array([[1, 4],
       [2, 5],
       [3, 6]])

"non-involving any library import" is a silly, non-productive requirement.