0

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.

Community
  • 1
  • 1
Dave Dave
  • 46
  • 1
  • 6
  • You mean `list`, `set`s are unordered in Python. – AChampion Jun 28 '16 at 02:20
  • Possible duplicate of [How can I add the corresponding elements of several lists of numbers?](http://stackoverflow.com/questions/11280536/how-can-i-add-the-corresponding-elements-of-several-lists-of-numbers). It isn't exactly the same, but it is close enough to be closed as a dupe. – zondo Jun 28 '16 at 02:28
  • If much of your code is like this, you should try R. With `a` and `b` as vectors, `c <- a-b` would already do what you want. – TigerhawkT3 Jun 28 '16 at 02:47

3 Answers3

2
c = [a1 - b1 for (a1, b1) in zip(a, b)]
p.magalhaes
  • 7,595
  • 10
  • 53
  • 108
2

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]
Iron Fist
  • 10,739
  • 2
  • 18
  • 34
0

Most people use numpy for numerical operations (although p.magalhaes has the answer for "pure" python).

import numpy as np
a=np.array([1,2,3,4])
b=np.array([1,0,1,5])
c = a - b
c

returns

array([ 0,  2,  2, -1])
Victor Chubukov
  • 1,345
  • 1
  • 10
  • 18