How to merge a multidimensional list into one list of tuples?

Suppose we have the following multi-dimensional list :

import numpy as np
lst = [[1,2,3], [4,5,6],[7,8,9]]

Expected output :

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

My problem is that the list ‘lst’ varies in size, otherwise I would achieve the wanted result with one for loop. I tried generalizing the task, here goes my attempt :

lst = [[1,2,3], [4,5,6],[7,8,9]]
test = np.array(list(zip(lst[i] for i in range(len(lst)))))

Clearly, this isn’t the result I wanted. Is there a straight forward way of doing so without iterating over each element in the list ?

Answer

You can use * to “unpack” lst:

lst = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
test = list(map(list, zip(*lst)))
print(test)

Prints:

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