1

I have below list of list called mylist and I want to take first element from each list and create a tuple. I want to do this for all n elements from list of list.

mylist = [[1,2,3], ['a', 'b', 'c'], [5, 8, 10], [100, 200, 30]]

convert to

mytuple = ((1,'a', 5, 100) ,(2,'b', 8, 200), (3,'c',10, 30))

I have managed to do it with below steps and I am sure there is better way :)

i = 0;
while(i < n):
    templist = (x[i] for x in mylist)
    newlist.append(tuple(templist))
    i += 1
ftuple = tuple(newlist) 

I have seen this link but haven't been able to find easier way looking at it SOlink1 Solink2

Community
  • 1
  • 1
oneday
  • 629
  • 1
  • 9
  • 32

2 Answers2

3

zip is what you need:

>>> mylist = [[1,2,3], ['a', 'b', 'c'], [5, 8, 10], [100, 200, 30]]
>>> zip(*mylist)  # In Python 3.x, this returns an iterator instead of a list
[(1, 'a', 5, 100), (2, 'b', 8, 200), (3, 'c', 10, 30)]
>>> tuple(zip(*mylist))
((1, 'a', 5, 100), (2, 'b', 8, 200), (3, 'c', 10, 30))
falsetru
  • 357,413
  • 63
  • 732
  • 636
1

You could use pandas data frame for this.

import pandas as pd

mylist = [[1,2,3], ['a', 'b', 'c'], [5, 8, 10], [100, 200, 30]]

df = pd.DataFrame(mylist).transpose()

print(df.values)
array([[1, 'a', 5, 100],
       [2, 'b', 8, 200],
       [3, 'c', 10, 30]], dtype=object)

For solution in the exact same form:

tuple([tuple(row) for row in df.values])
((1, 'a', 5, 100), (2, 'b', 8, 200), (3, 'c', 10, 30))
Sreejith Menon
  • 1,057
  • 1
  • 18
  • 27