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
  • 815
  • 2
  • 7
  • 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
  • 33,620
  • 7
  • 56
  • 73
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
  • 300,191
  • 65
  • 633
  • 696