0

I have a list of list something like this:

l=[[1,2,3],[1,2,3],[1,2,3]]

l1,l2,l3 = [],[],[]
for i in xrange(0,len(l)):
    l1.append(l[i][0])
    l2.append(l[i][1])
    l3.append(l[i][2])

So that I will get:

l1=[1,1,1]
l2=[2,2,2]
l3=[3,3,3]

I am interested in finding a better way of doing this. For example, if I were to add more values (l4, l5 ... etc.) could I find a way that would make it more dynamic rather than having to keep adding lists. Is there a way to map this somehow to give me something like:

new_l=[[1,1,1],[2,2,2],[3,3,3]]

Note: it is the positions that matter, these values were just used for simplicity.

Plato's Student
  • 53
  • 1
  • 1
  • 8

1 Answers1

3

Using zip function:

>>> list(zip(*l)) # You don't need list() in Python 2
[(1, 1, 1), (2, 2, 2), (3, 3, 3)]

This returns a list of tuples, if you need a list of lists:

>>> [list(x) for x in zip(*l)]
[[1, 1, 1], [2, 2, 2], [3, 3, 3]]
vaultah
  • 44,105
  • 12
  • 114
  • 143