hstay
hstay

Reputation: 1439

Add tuple to a list of tuples

How can I sum a tuple to a list of tuples such as:

>>> a = [(0, 1, 2), (3, 4, 5), (6, 7, 8)]
>>> b = (10, 20, 30)

the result being:

>>> c 
[(10, 21, 32), (13, 24, 35), (16, 27, 38)]

I know this can be easily solved with numpy:

>>> import numpy
>>> c = numpy.add(a, b).tolist()
>>> c
[[10, 21, 32], [13, 24, 35], [16, 27, 38]]

but I'd rather avoid numpy.

Upvotes: 3

Views: 1596

Answers (3)

dkasak
dkasak

Reputation: 2703

Define a function to sum two vectors:

def sum_vectors(a, b):
    return tuple(sum(z) for z in zip(a, b))

Use it to define a function for adding a vector to a list of vectors:

def add_vector_to_vectors(v, ws):
    return [sum_vectors(v, w) for w in ws]

Example usage:

>>> a = [(0, 1, 2), (3, 4, 5), (6, 7, 8)]
>>> b = (10, 20, 30)
>>> add_vector_to_vectors(b, a)
[(10, 21, 32), (13, 24, 35), (16, 27, 38)]

Upvotes: 2

squirl
squirl

Reputation: 1784

You can do this with list comprehension:

a = [(0, 1, 2), (3, 4, 5), (6, 7, 8)]
b = (10, 20, 30)
c = [[x + b[i] for i, x in enumerate(y)] for y in a]

c will be a list of lists, rather than a list of tuples. If that matters, you can do this instead:

c = [tuple(x + b[i] for i, x in enumerate(y)) for y in a]

Upvotes: 3

Jean-François Fabre
Jean-François Fabre

Reputation: 140307

one-liner using nested list comprehensions and the magic zip to interleave the fixed b triplet to add to the iterating element of a, no numpy needed:

a = [(0, 1, 2), (3, 4, 5), (6, 7, 8)]
b = (10, 20, 30)

c = [tuple([i+j for i,j in zip(e,b)]) for e in a]
print(c)

result:

[(10, 21, 32), (13, 24, 35), (16, 27, 38)]

EDIT: you could drop the tuple conversion if not needed:

c = [[i+j for i,j in zip(e,b)] for e in a]

Upvotes: 4

Related Questions