26

I can't 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 substracts List2 from List1, List3=[0,-2,4]! I know, that I somehow have to use the zip-function. By doing that I get: ([(3,3), (5,7), (6,2)]), but I don't know what to do now?

MichaelS
  • 5,941
  • 6
  • 31
  • 46
Linus Svendsson
  • 1,417
  • 6
  • 18
  • 21

5 Answers5

40

Try this:

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

This uses zip, list comprehensions, and destructuring.

Matt Fenwick
  • 48,199
  • 22
  • 128
  • 192
  • I like this way to do it.. I just can't get it to work (I haven't been working in python for a very long time)! I did this: def differences(xs,ys): [x1-x2 for (x1,x2) in zip(xs,ys)]? – Linus Svendsson Nov 19 '11 at 16:54
  • 1
    I used [np.subtract(x1, x2) for (x1, x2) in zip(List1, List2)] and it worked! – Alex Jul 05 '16 at 09:17
21

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]
Glorfindel
  • 21,988
  • 13
  • 81
  • 109
mac
  • 42,153
  • 26
  • 121
  • 131
7

You can use list comprehension, as @Matt suggested. you can also use itertools - more specifically, 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 a parameter for the list() constructor:

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

EDIT: As suggested by @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]
brandizzi
  • 26,083
  • 8
  • 103
  • 158
6

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

starrify
  • 14,307
  • 5
  • 33
  • 50
2

You can do it in the following way

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

that outputs [0, -2, 4]

anjaneyulubatta505
  • 10,713
  • 1
  • 52
  • 62