How to subtract two lists in python

Linus Svendsson picture Linus Svendsson · Nov 19, 2011 · Viewed 71.7k times · Source

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?

Answer

Matt Fenwick picture Matt Fenwick · Nov 19, 2011

Try this:

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

This uses zip, list comprehensions, and destructuring.