How to transpose a 2D-list into a column view?

Question:

I have this 2D-list

[["a1", "b1", "c1"], ["a2", "b2", "c2"]]

That I want to transpose to a column-view.
Each inner list has the same size.

Expected result :

[['a1', 'a2'], ['b1', 'b2'], ['c1', 'c2']]

I’m looking for a one-liner answer.

I’ve tried the code below that works but needs one line to initialize the l_col variable and two for the loop.

l = [["a1", "b1", "c1"], ["a2", "b2", "c2"]]

l_col = []
for i in range(len(l[0])):
    l_col.append([x[i] for x in l])

print(l_col)  # [['a1', 'a2'], ['b1', 'b2'], ['c1', 'c2']]

Thanks for your help.

Asked By: 0x0fba

||

Answers:

[[x[i] for x in l] for i in range(len(l[0]))]
Answered By: God Is One

In newer versions of Python, you can use:

A           = [["a1", "b1", "c1"], ["a2", "b2", "c2"]]
A_transpose = list(map(list,zip(*A)))

print('A_transpose: ', A_transpose)

# output:
#     A_transpose:  [['a1', 'a2'], ['b1', 'b2'], ['c1', 'c2']]

PS. For many applications, list(zip(*A)) also works. However, this short command returns tuples in the inner dimension: [('a1', 'a2'), ('b1', 'b2'), ('c1', 'c2')]. In the code above, we corrected this issue by introducing map(list,...).

Answered By: C-3PO
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.