Is it possible to delete multiple elements from a list at the same time? If I want to delete elements at index 0 and 2, and try something like del somelist, followed by del somelist, the second statement will actually delete somelist.
I suppose I could always delete the higher numbered elements first but I'm hoping there is a better way.
Probably not the best solution for this problem:
indices = 0, 2 somelist = [i for j, i in enumerate(somelist) if j not in indices]
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?