Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

removing elements incrementally from a list

Tags:

python

list

I've a list of float numbers and I would like to delete incrementally a set of elements in a given range of indexes, sth. like:

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

However, since I'm iterating over the same list, the indexes (range) are not valid any more for the new list. Does anybody has some suggestions on how to delete the elements properly?

Best wishes

like image 872
Javier Avatar asked Apr 14 '26 17:04

Javier


2 Answers

Do you really need to remove them incrementaly?

If not, you can do it like this:

del myList[beginIndex:endIndex+1]
like image 191
goedson Avatar answered Apr 16 '26 05:04

goedson


You can iterate from the end to beginning of the sequence:

for j in range(endIndex, beginIndex-1, -1):
    print ("remove [%d] => val: %g" % (j, myList[j]))
    del myList[j]
like image 25
pythonquick Avatar answered Apr 16 '26 05:04

pythonquick



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!