0

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?

  • 1
    possible duplicate of [Python - merge items of two lists into a list of tuples](http://stackoverflow.com/questions/2407398/python-merge-items-of-two-lists-into-a-list-of-tuples) –  Nov 16 '14 at 18:32

3 Answers3

1

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.

  • THANKS iCodez. also what do i set "zip(*(List1, List2, List3))", another list? because if i do that and i print it i get "" – rozzster Nov 18 '14 at 02:41
0

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)]
Mazdak
  • 105,000
  • 18
  • 159
  • 188
  • 1
    The OP said that he wants a list of tuples. The `zip` function already does this. Why import a function just to get the same result? `itertools.izip` is only more efficient if you do not convert the result to a list. –  Nov 16 '14 at 18:24
  • @iCodez hmm, i think your right , as i saw the good performance of `izip` for myself i just wanted to gave a good suggestion but for this question its more efficient to use `zip` ! – Mazdak Nov 16 '14 at 18:30
0

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)]
Ameet S M
  • 180
  • 2
  • 10