0

I'm trying to subtract sold stock from the total stock, however using this code, it subtracts each value in list B from each value in list A.

I want the corresponding value in list B to be subtracted from its corresponding value in list A, then move to the next set of numbers, opposed to subtracting every value from list B from each value in list A.

I am unsure how to modify my code, how do I achieve this?

for s in stocks:
    for q in quantities:
        print(float(s) - float(q))

what I want:

stock: [10, 20, 30]
quantities: [2, 3, 4]

output: 8, 17, 26

what is occurring:

stock: [10, 20, 30]
quantities: [2, 3, 4]

output: 8, 7, 6, 18, 17, 16, 28, 27, 26
U13-Forward
  • 69,221
  • 14
  • 89
  • 114

2 Answers2

2

Use a list comprehension with zip:

print([int(x) - int(y) for x, y in zip(stock, quantities)])

Output:

[8, 17, 26]

Or if you want a loop:

for x, y in zip(stock, quantities):
    print(int(x) - int(y))

Output:

8
17
26

Here is the docs:

Returns a list of tuples, where the i-th tuple contains the i-th element from each of the argument sequences or iterables.

Or use a map:

print(list(map(lambda x, y: int(x) - int(y), stock, quantities)))

Output:

[8, 17, 26]

Here is the docs:

Applies function to every item of an iterable and returns a list of the results. Your code isn't working because your doing something like:

10 - 2, 10 - 3, 10 - 4, 20 - 2 and so on...

So you're iterating through stock, and you're subtracting it by each value in quantities, not just the corresponding value.

U13-Forward
  • 69,221
  • 14
  • 89
  • 114
  • thanks for the response, I tried that but it doesnt seem to work. x and y are both strings so they cant be subtracted, using print(float(x) - float(y)) doesnt seem to work either as it prints out '2.0' and '-6.0' –  Jul 04 '19 at 03:27
  • @18649626842568 Try now, i edited my answer, please accept it if it works – U13-Forward Jul 04 '19 at 03:29
0

It would be better to use a dictionary to store your data in the first place, but for your use case, try using:

output = [int(stock[x]) - int(quantities[x]) for x, s in enumerate(stock)]
Evan Bloemer
  • 1,051
  • 2
  • 11
  • 31