How to subtract two lists in python [duplicate] How to subtract two lists in python [duplicate] python python

How to subtract two lists in python [duplicate]


Try this:

[x1 - x2 for (x1, x2) in zip(List1, List2)]

This uses zip, list comprehensions, and destructuring.


This solution uses numpy. It makes sense only for largish lists as there is some overhead in instantiate the numpy arrays. OTOH, for anything but short lists, this will be blazingly fast.

>>> import numpy as np>>> a = [3,5,6]>>> b = [3,7,2]>>> list(np.array(a) - np.array(b))[0, -2, 4]


Yet another solution below:

>>> a = [3,5,6]>>> b = [3,7,2]>>> list(map(int.__sub__, a, b)) # for python3.x[0, -2, 4]>>> map(int.__sub__, a, b) # and for python2.x[0, -2, 4]

ADDITION: Just check for the python reference of map and you'll see you could pass more than one iterable to map