1

So I have something like :

l1=[1,2,3]
l2=[4,5,6]
l3=[7,8,9]

Expected output is : ls=[[1,4,7],[2,5,8],[3,6,9]]

What it will be the most corect way to do that?

Rommel
  • 235
  • 2
  • 10

3 Answers3

7

Use zip and then list comprehension to turn the tuples into lists

[list(x) for x in zip(l1, l2, l3)]

Result:

[[1, 4, 7], [2, 5, 8], [3, 6, 9]]
Božo Stojković
  • 2,893
  • 1
  • 27
  • 52
5
>>> l1=[1,2,3]
>>> l2=[4,5,6]
>>> l3=[7,8,9]
>>> zip(l1, l2, l3)
[(1, 4, 7), (2, 5, 8), (3, 6, 9)]

The built-in function zip will help you with what you want.

jia hilegass
  • 493
  • 2
  • 12
5

zip the three lists:

>>> l1 = [1,2,3]
>>> l2 = [4,5,6]
>>> l3 = [7,8,9]
>>> zip(l1,l2,l3)
[(1, 4, 7), (2, 5, 8), (3, 6, 9)]

Use a list comprehension to cast the tuples into lists to have a list of lists:

>>> [list(i) for i in zip(l1,l2,l3)]
[[1, 4, 7], [2, 5, 8], [3, 6, 9]]
Moses Koledoye
  • 77,341
  • 8
  • 133
  • 139