-3

I can't seem to get the results from a for loop equations to add up.

for i in inventory:
    indexlist = inventory.index(i)
    valueperproduct = [(inventory[indexlist] * cost[indexlist])]
    print(valueperproduct)

total = 0
for i in valueperproduct:
    total += i
print(total)

This is what it returns:

0 pen 2 1.5
1 watch 3 2.5
2 ruler 4 4.5
3 bike 5 3.3
[3.0]
[7.5]
[18.0]
[16.5]
16.5

What did I do wrong?

mkrieger1
  • 19,194
  • 5
  • 54
  • 65
kschu
  • 3
  • 1
  • Combine the loops into one or at least make valueproduct an array outside of the loop and append elements inside of it. – luk2302 Apr 17 '23 at 10:20
  • 1
    You are perfectly adding the values from the list containing one element. – mkrieger1 Apr 17 '23 at 10:21
  • Does this answer your question? [How can I collect the results of a repeated calculation in a list, dictionary etc. (or make a copy of a list with each element modified)?](https://stackoverflow.com/questions/75666408/how-can-i-collect-the-results-of-a-repeated-calculation-in-a-list-dictionary-et) – mkrieger1 Apr 17 '23 at 10:27
  • how can your code produce lines like "0 pen 2 1.5"? there's an inconsistency between the 4 first lines and the next 4 ones that doesn't make sense. Are you sure that the code you posted produces the output you posted? – Sembei Norimaki Apr 17 '23 at 10:32

1 Answers1

0

You have declared 'valueperproduct' in your for loop and so with each iteration you are overwriting the previous values. I think declaring the array outside of the loop and appending to it will give the desired result.

valueperproduct = []
for i in inventory:
    indexlist = inventory.index(i)
    valueperproduct.append(inventory[indexlist] * cost[indexlist])
    print(valueperproduct)

total = 0
for i in valueperproduct:
    total += i
print(total)
AxFrz
  • 41
  • 2