tags:

views:

69

answers:

3

I would like to either extend or append a list to the content of another list: I've got the following:

l = (('AA', 1.11,'DD',1.2), ('BB', 2.22, 'EE', 2.3), ('CC', 3.33, 'FF', 3.45))
ls = [('XX', 7.77), ('YY', 8.88), ('ZZ', 9.99)]
m = ['first', 'second', 'third']
for i in range(len(l)):
    result = []
    for n in m:
        if n == "first":
            r=[]
            for word, number in ls[i]:
                temp = [word, number]
                r.append(temp)
            for t in r:
                result.extend(t)
            print result

I would like to see the following result when the 'result' is printed out in the above code (each in newline):

['AA', 1.11, 'XX', 7.77]
['BB', 2.22, 'YY', 8.88]
['CC', 3.33, 'ZZ', 9.99]

Many thanks in advance.

+10  A: 

All you need is zip:

l = (('AA', 1.11), ('BB', 2.22), ('CC', 3.33))
ls = [('XX', 7.77), ('YY', 8.88), ('ZZ', 9.99)]

for x,y in zip(l,ls):
    print(list(x+y))

# ['AA', 1.1100000000000001, 'XX', 7.7699999999999996]
# ['BB', 2.2200000000000002, 'YY', 8.8800000000000008]
# ['CC', 3.3300000000000001, 'ZZ', 9.9900000000000002]
unutbu
Thanks a lot, but I'm sorry I forgot to mention that the 'l' could be l=(('AA', 1.11,'DD',1.2), ('BB', 2.22, 'EE', 2.3), ('CC', 3.33, 'FF', 3.45)). I don't think zip() works in this case though. Any way out?
DGT
@DGT: why don't you try and see. It does work.
SilentGhost
Yes, you're right. Indeed it does works. I wasn't typing things right. Thanks a lot, unutbu.
DGT
+1  A: 

You want the zip function:

>>> for x in zip(l, ls):
>>>     list1, list2 = x
>>>     print list1 + list2

>>> ['AA', 1.1100000000000001, 'XX', 7.7699999999999996]
>>> ['BB', 2.2200000000000002, 'YY', 8.8800000000000008]
>>> ['CC', 3.3300000000000001, 'ZZ', 9.9900000000000002]

1: http://docs.python.org/library/functions.html#zip "zip

twneale
Thanks a lot for your help.
DGT
A: 

Here's one way:

import itertools

for a, b, c in itertools.izip(l, ls, m):
    result = list(a) + list(b) +  [c]
    print result

The output:

['AA', 1.1100000000000001, 'XX', 7.7699999999999996, 'first']
['BB', 2.2200000000000002, 'YY', 8.8800000000000008, 'second']
['CC', 3.3300000000000001, 'ZZ', 9.9900000000000002, 'third']
ars