0

I have a list

a = [[1,2],[3,4],[5,6],[7,8],[9,10]]

Result

New_a = [[1,3,5,7,9],[2,4,6,8,10]]

Any smart way or python built-in function can solve the problem?

3 Answers 3

7
list(zip(*a))
Out[6]: [(1, 3, 5, 7, 9), (2, 4, 6, 8, 10)]

Explanation: zip takes two or more iterables and stitches them together where "the i-th element comes from the i-th iterable argument." The star operator unpacks a so that you zip the elements together, not the sublists.

Sign up to request clarification or add additional context in comments.

2 Comments

why do you need list?
@lukas in python3 zip returns a generator object. You can drop the list in python2.
2

You can use zip in conjunction with the flattening operator *:

[list(t) for t in zip(*a)]

You could also just use zip(*a) by itself if (1) you're using Python 2 and (2) you don't mind getting a list of tuples instead of a list of lists.

Comments

1
import numpy as np
a = np.array([[1,2],[3,4],[5,6],[7,8],[9,10]])

Result:

>>> a
array([[ 1,  2],
       [ 3,  4],
       [ 5,  6],
       [ 7,  8],
       [ 9, 10]])
>>> a.T
array([[ 1,  3,  5,  7,  9],
       [ 2,  4,  6,  8, 10]])

1 Comment

Matrixbots! Transpose and move out!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.