0

I have a list of 4 list show below.

list1 = [['a', 'b', 'c'], ['d', 'e', 'f'], ['g', 'h', 'i'], ['j', 'k', 'l']]

How do I create a list of list by element position so that the new list of list is as follows?

list2 = [['a', 'd', 'g', 'j'], ['b', 'e', 'h', 'k'], ['c', 'f', 'i', 'l']]

I tried using a for loop such as

res = []
for listing in list1:
    for i in list:
        res.append(i)

however it just created a single list.

Chase
  • 1

1 Answers1

0

Use zip with the * operator to zip all of the sublists together. The resulting tuples will have the list contents you want, so just use list() to convert them into lists.

>>> list1 = [['a', 'b', 'c'], ['d', 'e', 'f'], ['g', 'h', 'i'], ['j', 'k', 'l']]
>>> [list(z) for z in zip(*list1)]
[['a', 'd', 'g', 'j'], ['b', 'e', 'h', 'k'], ['c', 'f', 'i', 'l']]
Samwise
  • 68,105
  • 3
  • 30
  • 44