Deleting multiple elements from a list

For some reason I don’t like any of the answers here.
Yes, they work, but strictly speaking most of them aren’t deleting elements in a list, are they? (But making a copy and then replacing the original one with the edited copy).

Why not just delete the higher index first?

Is there a reason for this?
I would just do:

for i in sorted(indices, reverse=True):
    del somelist[i]

If you really don’t want to delete items backwards, then I guess you should just deincrement the indices values which are greater than the last deleted index (can’t really use the same index since you’re having a different list) or use a copy of the list (which wouldn’t be ‘deleting’ but replacing the original with an edited copy).

Am I missing something here, any reason to NOT delete in the reverse order?

Leave a Comment