That's what the zip
function is for.
>>> A = [ [0,2,3,4], [0,1,1,2] ]
>>> B = [list(x) for x in zip(*A[::-1])]
>>> B
[[0, 0], [1, 2], [1, 3], [2, 4]]
if you don't need your elements to be lists (i.e. tuples are fine, too), this shortens to
>>> zip(*A[::-1])
[(0, 0), (1, 2), (1, 3), (2, 4)]
in Python 2 and
>>> list(zip(*A[::-1]))
[(0, 0), (1, 2), (1, 3), (2, 4)]
in Python 3.
Explanation of the syntax:
A[::-1]
is reversing A
:
>>> A[::-1]
[[0, 1, 1, 2], [0, 2, 3, 4]]
The reversed list is then passed in an unpacked form (notice the *
) to the zip
function, which is equivalent to
>>> zip([0, 1, 1, 2], [0, 2, 3, 4])
[(0, 0), (1, 2), (1, 3), (2, 4)]
and zip
will build tuples from the first, second, ..., n'th elements from each iterable.
edit:
Minor improvement:
>>> zip(*reversed(A))
[(0, 0), (1, 2), (1, 3), (2, 4)]
should be more memory efficient because reversed
gives you an iterator, A[::-1]
gives you a complete list, which we don't really need.