Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to subtract two lists in python [duplicate]

Tags:

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?

like image 470
Linus Svendsson Avatar asked Nov 19 '11 12:11

Linus Svendsson


People also ask

Can you subtract two lists in Python?

Use Numpy to Subtract Two Python Lists One of the methods that numpy provides is the subtract() method. The method takes two numpy array s as input and provides element-wise subtractions between the two lists.

How do you subtract a list from a list in Python?

Method 3: Use a list comprehension and set to Find the Difference Between Two Lists in Python. In this method, we convert the lists into sets explicitly and then simply reduce one from the other using the subtract operator.

How do you subtract two lists the same size in Python?

subtract(x1, x2) for (x1, x2) in zip(List1, List2)] and it worked!


1 Answers

Try this:

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

This uses zip, list comprehensions, and destructuring.

like image 54
Matt Fenwick Avatar answered Oct 18 '22 20:10

Matt Fenwick