oneday - 3 months ago 5x
Python Question

# creating new tuple with index i from each list of list

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

`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))
``````