jossi
jossi

Reputation: 79

List Python Operation

I got this list:

input = [[1,2,3,4],[5,6,7,8],[9,10,11,12]]

I want to make new lists with each index item:

i.e.

output = [[1,5,9],[2,6,10],[3,7,11],[4,8,12]]

Upvotes: 4

Views: 288

Answers (2)

Sven Marnach
Sven Marnach

Reputation: 601679

Use zip():

input = [[1,2,3,4],[5,6,7,8],[9,10,11,12]]
output = zip(*input)

This will give you a list of tuples. To get a list of lists, use

output = map(list, zip(*input))

Upvotes: 4

unutbu
unutbu

Reputation: 879611

This is a canonical example of when to use zip:

In [6]: inlist = [[1,2,3,4],[5,6,7,8],[9,10,11,12]]

In [7]: out=zip(*inlist)

In [8]: out
Out[8]: [(1, 5, 9), (2, 6, 10), (3, 7, 11), (4, 8, 12)]

Or, to get a list of lists (rather than list of tuples):

In [9]: out=[list(group) for group in zip(*inlist)]

In [10]: out
Out[10]: [[1, 5, 9], [2, 6, 10], [3, 7, 11], [4, 8, 12]]

Upvotes: 8

Related Questions