0

It should work like

input: list([[1,1,1],[2,2,2],[3,3,3]])
output: [[1,2,3], [1,2,3], [1,2,3]]

so far i have done this:

def list(m):
    list2=[]
    for i in range(0, len(m)):
            list2.append([x[i] for x in m])
    return(list2)

It's not working every time..

For example:

it's working for

input: list([[1,1,1],[2,2,2],[3,3,3]])

but not for

input: list([[1,3,5],[2,4,6]])
Ma0
  • 15,057
  • 4
  • 35
  • 65
Sawan
  • 19
  • 1
  • 4

1 Answers1

2

You would usually do that in Python using the zip function:

inp = list([[1,1,1],[2,2,2],[3,3,3]])
output = list(map(list, zip(*inp)))
print(output)
>>> [[1, 2, 3], [1, 2, 3], [1, 2, 3]]

The additional map call is to convert the elements returned by zip, that are tuples, into lists, but if you are okay with tuples you can just do:

inp = list([[1,1,1],[2,2,2],[3,3,3]])
output = list(zip(*inp))
print(output)
>>> [(1, 2, 3), (1, 2, 3), (1, 2, 3)]

Also, the outer list is only necessary in Python 3, where zip returns a generator, but not in Python 2.

jdehesa
  • 58,456
  • 7
  • 77
  • 121