0

I want to iterate through "my_list" and if the item is an integer, look up the same index in the "other_list", then subtract the item from "other_list" from the same index item in "my_list". Then, append the result to "new_list". If the item is not an integer, it does not do a calculation and just adds the string to "new_list."

my_list = [3, 5, 2, ' ', 0, 17, 20, 22, ' ', 5, 18, 19, 8, ' ', 6, 17]
other_list = [5, 17, 8, ' ', 4, 13, 3, 18, ' ', 5, 17, 8, 4, ' ', 13, 3]
new_list = []

for i in my_list:

    if type(i) is int:
        x = i - other_list[my_list.index(i)]
        new_list.append(x)
    
    else:
        
       new_list.append(i)

print(new_list)

The result I get is [-2, -12, -6, ' ', -4, 4, 17, 4, ' ', -12, 1, 11, 4, ' ', -7, 4].

The "-12 and the last "4" calculation isn't correct. It should be "0" and "14".

Could anyone help to explain why I am getting that result?

PM 77-1
  • 12,933
  • 21
  • 68
  • 111
ajdesanti
  • 9
  • 3
  • 1
    ```my_list.index(i)``` finds the *first* index of i. Your logic breaks when you have duplicate values. Change your loop to ```for index, i in enumerate(my_list)``` and go from there – Homer512 Aug 04 '22 at 13:10
  • 1
    `my_list.index(i)` will return the *first* index for which there is `i` in the list. So this won't work if you have duplicate values, like 5 here. Use [zip](https://docs.python.org/3/library/functions.html#zip) to iterate on the lists in parallel. – Thierry Lathuille Aug 04 '22 at 13:11

0 Answers0