0

I have a list

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

I want to convert it to

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

How can I do this?

veena
  • 765
  • 2
  • 6
  • 11

2 Answers2

4

Try using zip function, and use *a to unpack:

a = [[1, 2, 3], [4, 5, 6], [7, 8, 9], [10, 11, 12]]
print zip(*a)
>>> [(1, 4, 7, 10), (2, 5, 8, 11), (3, 6, 9, 12)]

If you want lists instead of tuples:

print map(list, zip(*a))
>>> [[1, 4, 7, 10], [2, 5, 8, 11], [3, 6, 9, 12]]
Christian Tapia
  • 32,670
  • 6
  • 50
  • 72
4

use zip.

print zip(*a)

If you really want a list of lists, instead of a list of tuple:

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

will do the trick (and, as a bonus, this works the same on python2.x and python3.x)

mgilson
  • 283,004
  • 58
  • 591
  • 667