Given a list of numbers:
L = [1, 2, 3, 4, 5]
How do I delete an element, let’s say 3, from the list while I iterate over it?
I tried the following code but it didn’t do it:
for el in L:
if el == 3:
del el
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
Best is usually to proceed constructively — build the new list of the items you want instead of removing those you don’t. E.g.:
the list comprehension builds the desired list and the assignment to the “whole-list slice”,
L[:], ensure you’re not just rebinding a name, but fully replacing the contents, so the effects are identically equal to the “removals” you wanted to perform. This is also fast.If you absolutely, at any cost, must do deletions instead, a subtle approach might work:
nowhere as elegant, clean, simple, or well-performing as the listcomp approach, but it does do the job (though its correctness is not obvious at first glance and in fact I had it wrong before an edit!-). “at any cost” applies here;-).
Looping on indices in lieu of items is another inferior but workable approach for the “must do deletions” case — but remember to reverse the indices in this case…:
indeed this was a primary use case for
reversedback when we were debating on whether to add that built-in —reversed(range(...isn’t trivial to obtain withoutreversed, and looping on the list in reversed order is sometimes useful. The alternativeis really easy to get wrong;-).
Still, the listcomp I recommended at the start of this answer looks better and better as alternatives are examined, doesn’t it?-).