Dave Dave - 1 year ago 71

Python Question

I want to subtract the values inside of two lists.

`a = [1,2,3,4]`

b = [1,0,1,5]

c = a - b

#c should be = [0,2,2,-1]

The answer to How can I add the corresponding elements of several lists of numbers? is simular, but alot of the answers on it are only applicable to adding.

Please answer with how to subtract, if possible.

Answer

Probably `itertools.starmap`

would be useful in your case:

```
>>> a = [1,2,3,4]
>>> b = [1,0,1,5]
>>>
>>> import itertools as it
>>>
>>> import operator as op
>>>
>>> list(it.starmap(op.sub, zip(a,b)))
[0, 2, 2, -1]
```

OR:

```
>>> [item for item in it.starmap(op.sub, zip(a,b))]
[0, 2, 2, -1]
```

Source (Stackoverflow)