user4544020
user4544020

Reputation:

Function that returns a list of tuples.

Id like to write a procedure that returns a list of tuples. The kth element in each tuple corresponding to the sum of the kth elements of the tuples in the lists given as input.

A = [(1,2), (3,4)] B = [(10,20), (30,40)]

will return

[(11,22) , (33, 44)]

def sumtuple(A,B):
    ret = []
    for K in A:
        for L in B:
            ret.append(K[0] + L[0], K[1] + L[1])
return ret

There is some clear flaws with my attempt, it gives some undesirable results, for example it gives (13,24) in the answer. I can see why this is going wrong. But what i can't do is write some code that gives me the result i want.

I'm a novice, please be kind.

Upvotes: 1

Views: 7398

Answers (4)

Dan D.
Dan D.

Reputation: 74645

Use zip to loop over both lists at the same time:

def sumtuple(A,B):
    ret = []
    for a, b in zip(A, B):
        ret.append((a[0] + b[0], a[1] + b[1]))

    return ret

Upvotes: 2

itzMEonTV
itzMEonTV

Reputation: 20339

Made from your function :)

def sumtuple(A,B):
    b=[]
    for i in range(len(A)):
        l=[]
        for j in range(len(A[i])):
            l.append(A[i][j]+B[i][j])
        l=tuple(l)
        b.append(l)
    return b

Upvotes: 0

Padraic Cunningham
Padraic Cunningham

Reputation: 180401

using map with operator.add and zip_longest to work for uneven length lists:

from operator import add 
from itertools import zip_longest

print([tuple(map(add, a, b)) for a,b in zip_longest(A,B,fillvalue=(0,0))])
[(11, 22), (33, 44)]

You won't lose data if one list is a different length:

A = [(1, 2), (3, 4)]
B = [(10, 20), (30, 40),(10,12)]
print([tuple(map(add, a, b)) for a,b in zip_longest(A,B,fillvalue=(0,0))])
[(11, 22), (33, 44), (10, 12)]

Upvotes: 0

Hackaholic
Hackaholic

Reputation: 19733

you can try like this:

def sumtuple(A,B):
    ret = []
    for K in range(len(A)):
        ret.append(A[K][0] + B[K][0], A[K][1] + B[K][1])
    return ret

Upvotes: 0

Related Questions