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?
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.
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.
subtract(x1, x2) for (x1, x2) in zip(List1, List2)] and it worked!
Try this:
[x1 - x2 for (x1, x2) in zip(List1, List2)]
This uses zip
, list comprehensions, and destructuring.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With