Lets say I have three list:
List1 = [1,2,3]
List2 = [4,5,6]
List3 = [7,8,9]
And now I want to create a new list with tuple elements, but use the data from my previous lists:
NewList = [(1,4,7), (2,5,6), (3,6,9)]
How can this be done?
Lets say I have three list:
List1 = [1,2,3]
List2 = [4,5,6]
List3 = [7,8,9]
And now I want to create a new list with tuple elements, but use the data from my previous lists:
NewList = [(1,4,7), (2,5,6), (3,6,9)]
How can this be done?
All you need is zip
:
>>> List1 = [1,2,3]
>>> List2 = [4,5,6]
>>> List3 = [7,8,9]
>>> zip(*(List1, List2, List3))
[(1, 4, 7), (2, 5, 8), (3, 6, 9)]
>>>
Also, you will notice that the third element of the second tuple is different. I think you have a typo in your question.
As an alternative answer if performance is important for you , i suggest use itertools.izip
instead built-in zip()
:
>>> l=[List1,List2,List3]
>>> from itertools import izip
>>> list(izip(*l))
[(1, 4, 7), (2, 5, 8), (3, 6, 9)]
This is not the best way to do it, just as an alternative.
>>> NewList = []
>>> i = 0
>>> while i <= len(List1)-1 :
NewList.append(tuple(j[i] for j in (List1, List2, List3)))
i+=1
>>>NewList
[(1, 4, 7), (2, 5, 8), (3, 6, 9)]