How to subtract two lists in python

I cannot figure out how to make a function in python that can calculate this:

List1=[3,5,6] List2=[3,7,2] 

and the result should be a new list that forces List2 out of List1, List3=[0,-2,4] ! I know that I somehow have to use the zip function. By doing this, I get: ([(3,3), (5,7), (6,2)]) , but I don’t know what to do now?

+7
source share
5 answers

Try the following:

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

In this case, zip , lists, and destructuring are used.

+15
source

This solution uses numpy . This only makes sense for large lists, as there is some overhead to creating numpy arrays. OTOH, for anything but short lists, it will be incredibly fast.

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

You can use list comprehension , as @Matt suggested. you can also use itertools - more precisely, the imap() function:

 >>> from itertools import imap >>> from operator import sub >>> a = [3,5,6] >>> b = [3,7,2] >>> imap(int.__sub__, a, b) <itertools.imap object at 0x50e1b0> >>> for i in imap(int.__sub__, a, b): ... print i ... 0 -2 4 

Like all itertools funcitons, imap() returns an iterator. You can generate a list passing it as an argument to the list() constructor:

 >>> list(imap(int.__sub__, a, b)) [0, -2, 4] >>> list(imap(lambda m, n: mn, a, b)) # Using lambda [0, -2, 4] 

EDIT . As suggested in @Cat below, it would be better to use the operator.sub() function with imap() :

 >>> from operator import sub >>> list(imap(sub, a, b)) [0, -2, 4] 
+6
source

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 the python map link and you will see that you can go through more than one iterable to map

+3
source

You can do it as follows

 List1 = [3,5,6] List2 = [3,7,2] ans = [List1[i]-List2[i] for i in xrange(min(len(List1), len(List2)))] print ans 

which outputs [0, -2, 4]

0
source

All Articles