+5 votes
in Programming Languages by (73.8k points)

I want to subtract one list from another list element-wise, but the subtract operation gives an error:

>>> x=[12,13,14,15]

>>> y=[2,3,4,5]

>>> x-y

Traceback (most recent call last):

  File "<stdin>", line 1, in <module>

TypeError: unsupported operand type(s) for -: 'list' and 'list'

How can I do element-wise subtraction?

1 Answer

+1 vote
by (349k points)
selected by
 
Best answer

If you want to use the subtract operator '-', you need to convert your lists to NumPy arrays.

E.g.

>>> import numpy as np

>>> x=[12,13,14,15]
>>> y=[2,3,4,5]
>>> list(np.array(x)-np.array(y))
[10, 10, 10, 10]

You can also use subtract() function of Numpy for element-wise subtraction.

E.g.

>>> import numpy as np

>>> x=[12,13,14,15]
>>> y=[2,3,4,5]
>>> list(np.subtract(x,y))
[10, 10, 10, 10]


...