I have two numeric lists, a, b that I am trying to subtract like this; b - a.
I want this to be easy for a beginner to understand so I don't want to import classes or libraries.
This is what I have tried, and it works:
a = [420, 660, 730, 735]
b = [450, 675, 770, 930]
i = 0
j = len(a)
difference = []
while i < j:
difference.append(b[i] - a[i])
i += 1
print (difference)
>>[30, 15, 40, 195] **the correct result**
However, there must be a simpler way of doing this without importing classes or libraries that I am missing.
A simple way to show this would be:
a = [420, 660, 730, 735]
b = [450, 675, 770, 930]
print([v2 - v1 for v1, v2 in zip(a, b)])
zip will create a tuple between each of the elements in your list. So if you run zip alone you will have this:
zip(a, b)
[(420, 450), (660, 675), (730, 770), (735, 930)]
Then, to further analyze what is happening in the answer I provided, what you are doing is iterating over each element in your list, and then specifying that v1 and v2 are each item in your tuple. Then the v2 - v1 is pretty much doing your math operation. And all of this is wrapped inside what is called a list comprehension.
If you are still convinced that you still don't want to use zip at all, and if your example is using two equal lists, then what I suggest is to drop the while loop and use a for instead. And your solution will be very similar to what you already have, but as such:
n = []
for i, v in enumerate(a):
n.append(b[i] - v)
print(n)
So, you have to create a new list that will hold your new data. Use enumerate so you get your index and value through each iteration, and append your math operation to your new list.
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