hstay - 1 year ago 93

Python Question

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.

Answer Source

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]
```