How to mathematically subtract two lists in python?

Gareth Bale picture Gareth Bale · Apr 19, 2014 · Viewed 40.6k times · Source

I know subtraction of lists is not supported in python, however there are some ways to omit the common elements between two lists. But what I want to do is subtraction of each element in one list individually with the corresponding element in another list and return the result as an output list. How can I do this?

     A = [3, 4, 6, 7]
     B = [1, 3, 6, 3]
     print A - B  #Should print [2, 1, 0, 4]

Answer

Thanakron Tandavas picture Thanakron Tandavas · Apr 19, 2014

Use operator with map module:

>>> A = [3, 4, 6, 7]
>>> B = [1, 3, 6, 3]
>>> map(operator.sub, A, B)
[2, 1, 0, 4]

As @SethMMorton mentioned below, in Python 3, you need this instead

>>> A = [3, 4, 6, 7]
>>> B = [1, 3, 6, 3]
>>> list(map(operator.sub, A, B))
[2, 1, 0, 4]

Because, map in Python returns an iterator instead.