Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<blockquote> <p>Eine Minuten bitte, Ich hap eine kleine Problemo avec diese Religione. -- Eddie Izzard (doing his impression of Martin Luther)</p> </blockquote> <p>Deleting by reverse-iterating over a list to preserve the iterator <em>is</em> a common solution to this problem. But another solution is to change this into a different problem. Instead of deleting items from the list using some criteria (in your case, the index exists in a list of indexes to be deleted), create a new list that leaves out the offending items.</p> <pre><code>L[:] = [ item for i,item in enumerate(L) if i not in I ] </code></pre> <p>For that matter, where did you come up with the indexes in <code>I</code> in the first place? You could combine the logic of getting the indexes to be removed and building the new list. Assuming this is a list of objects and you only want to keep those that pass an <code>isValid</code> test:</p> <pre><code>L[:] = [ item for item in L if item.isValid() ] </code></pre> <p>This is much more straightforward than:</p> <pre><code>I = set() for i in range(len(L)): if not L[i].isValid(): I.add(i) for i in sorted(I, reverse=True): del L[i] </code></pre> <p>For the most part, I turn any question about "how to delete from a list the items that I don't want" into "how to create a new list containing just the items I want".</p> <p>EDITED: changed "L = ..." to "L[:] = ..." per Alex Martelli's answer to <a href="https://stackoverflow.com/questions/1352885/remove-elements-as-you-traverse-a-list-in-python">this question</a>.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload