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[0]
, followed by del somelist[2]
, the second statement will actually delete somelist[3]
.
I suppose I could always delete the higher numbered elements first but I’m hoping there is a better way.
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?