11

Suppose I have two lists:

t1 = ["abc","def","ghi"]  
t2 = [1,2,3]

How can I merge it using python so that output list will be:

t =  [("abc",1),("def",2),("ghi",3)]

The program that I have tried is:

t1 = ["abc","def"]  
t2 = [1,2]         
t = [ ]  
for a in t1:  
        for b in t2:  
                t.append((a,b))  
print t

Output is:

[('abc', 1), ('abc', 2), ('def', 1), ('def', 2)]

I don't want repeated entries.

Cilyan
  • 7,883
  • 1
  • 29
  • 37
Madhusudan
  • 435
  • 2
  • 9
  • 26

2 Answers2

25

In Python 2.x, you can just use zip:

>>> t1 = ["abc","def","ghi"]
>>> t2 = [1,2,3]
>>> zip(t1, t2)
[('abc', 1), ('def', 2), ('ghi', 3)]
>>>

However, in Python 3.x, zip returns a zip object (which is an iterator) instead of a list. This means that you will have to explicitly convert the results into a list by putting them in list:

>>> t1 = ["abc","def","ghi"]
>>> t2 = [1,2,3]
>>> zip(t1, t2)
<zip object at 0x020C7DF0>
>>> list(zip(t1, t2))
[('abc', 1), ('def', 2), ('ghi', 3)]
>>>
  • Could be wrong, but I think you read it right the first time. I think the zipped list is what the OP wants, what you've written is what the OP's attempt produced, but the OP "[doesn't] want repeated entries". – DSM Feb 10 '14 at 18:20
  • @DSM - That's it. I need another coffee... –  Feb 10 '14 at 18:21
6

Use zip:

>>> t1 = ["abc","def","ghi"]
>>> t2 = [1,2,3]
>>> list(zip(t1,t2))
[('abc', 1), ('def', 2), ('ghi', 3)]
# Python 2 you do not need 'list' around 'zip' 

If you do not want repeated items, and you do not care about order, use a set:

>>> l1 = ["abc","def","ghi","abc","def","ghi"]
>>> l2 = [1,2,3,1,2,3]
>>> set(zip(l1,l2))
set([('def', 2), ('abc', 1), ('ghi', 3)])

If you want to uniquify in order:

>>> seen=set()
>>> [(x, y) for x,y in zip(l1,l2) if x not in seen and (seen.add(x) or True)]
[('abc', 1), ('def', 2), ('ghi', 3)]
dawg
  • 98,345
  • 23
  • 131
  • 206