0

Given the following list:

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

My goal is to end up with the following:

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

My problem with this is, a does not have a fixed length ( if it did, I wouldn't need any help ). The length of the list is dynamic. Each loop pass adds a number to each sublist.

For example, a would look like this after the next loop pass:

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

And b would look like this now:

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

I need the nth element from each sublist each time.

I tried list comprehension, searched this forum, but found no solution to my problem.

python_ftw
  • 45
  • 5

1 Answers1

2

If you don't want to use map you can simply use list comprehension and the unpack operator *:

>>> a = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
>>> [[x, y, z] for x, y, z in zip(*a)]
[[1, 4, 7], [2, 5, 8], [3, 6, 9]]

But this is only guaranteed if your list a only contains lists as elements of same length.

Wolric
  • 701
  • 1
  • 2
  • 18