Sum some elements of a list while taking care not to reuse an already used index

Hi there! I have a problem. I’d like to sum 3 of 4 elements of a list taking care not to use an index already used in the previous operations. Let me explain.
For example, I have:

list = [1, 2, 3, 4]

I’d like to:

  • sum everything in the list except 1 i.e. 2 + 3 + 4
  • sum everything in the list except 2 i.e. 1 + 3 + 4
  • sum everything in the list except 3 i.e. 1 + 2 + 4
  • sum everything in the list except 4 i.e. 1 + 2 + 3

This is how I proceeded

sum_item, tab_sum, tab_index = 0, [], []
for index in range(len(list)):
     if(index == len(arr)):
          continue
     elif(index in tab_index):
          continue
     else:
          sum_item += arr[index]
     tab_index.append(index)

But it doesn’t work

There is way too much going on in your code for this task. Rethink your approach.
Consider taking the sum of the whole list and then subtracting a value from that perhaps.

You can do what you want in a very small amount of code with no conditional statements or seperate arrays

1 Like

Thank you for your idea. I believe that I understood what you meant. I used a new approach and it works perfectly:

    sum_list, keep_list = 0, []
    for i in range(len(arr)):
        sum_list = sum(arr) - arr[i]
        keep_list.append(sum_list)

Actually, I wanted to sum the items on the list and compare them to see the min and the max