1

Let's say we have this:

list1 = [['a', 'b', 'c'], ['1', '2', '3'], ['x', 'y', 'z'], ['4', '5', '6']]

The output I'm looking for is:

[['a', '1', 'x', '4'], ['b', '2', 'y', '5'], ['c', '3', 'z', '6']]

Note: the length of list1 could be longer or shorter, shouldn't matter.

Note: len(list1[0]) = len(list1[1]) = len(list1[any_index]) which means all of the sublists in the main list will have the same length.

I've tried using different for loops using different ways to use the indexes but I can't get anything to work, can someone help me out? I'm not looking for code in the answer, just how I would do it.

1 Answers1

2

If you are okay with tuples, just use:

a = zip(*list1)
# [('a', '1', 'x', '4'), ('b', '2', 'y', '5'), ('c', '3', 'z', '6')]

Otherwise, just do

a = [list(x) for x in zip(*list1)]
# [['a', '1', 'x', '4'], ['b', '2', 'y', '5'], ['c', '3', 'z', '6']]
Julien Spronck
  • 15,069
  • 4
  • 47
  • 55