Removing items step by step from the list

I have a list of floating point numbers, and I would like to delete a set of elements in a given range of indices step by step, i.e.:

for j in range(beginIndex, endIndex+1):
   print ("remove [%d] => val: %g" % (j, myList[j]))
   del myList[j]

However, since I am repeating the same list, the indexes (range) are no longer valid for the new list. Does anyone have any suggestions for removing items correctly?

Regards

+3
source share
3 answers

Do you really need to remove them gradually?

If not, you can do it like this:

del myList[beginIndex:endIndex+1]
+9
source

You can iterate from end to start of a sequence:

for j in range(endIndex, beginIndex-1, -1):
    print ("remove [%d] => val: %g" % (j, myList[j]))
    del myList[j]
+2
source

Something like that?

>>> list1 = [1,2,3,4,5,6]
>>> start, end = 2, 4
>>> list1[:start] + list1[end:]
[1, 2, 5, 6]
+1
source

Source: https://habr.com/ru/post/1746167/


All Articles