How to remove things from a list while iterating?

How to remove things from a list while iterating?

I’m iterating over a list of tuples in Python, and have always been trying to take them off if they meet certain criteria.

Exactly What must I use in place of code_to_remove_tup ? I cannot figure out how to take away the item in this manner.

25 Responses 25

channing tatum dating

You can make use of an inventory comprehension to create a list that is new just the elements you never want to eliminate

Or, by assigning to your piece somelist[ ] , you can mutate the list that is existing contain just the items you would like

This process could possibly be helpful if there are more references to somelist that want to mirror the changes.

In the place of a comprehension, you could also use itert ls . In Python 2

The answers suggesting list comprehensions are ALMOST proper — except it the same name the old list as, they do NOT modify the old list in place that they build a completely new list and then give. That’s not the same as that which you’d be doing by selective treatment, as in @Lennart’s suggestion — it’s faster, but if your list is accessed via multiple recommendations the fact you’re just reseating among the recommendations and never altering the list object itself can cause simple, disastrous pests.

Happily, it is incredibly very easy to get both the speed of list comprehensions AND the needed semantics of in-place alteration — simply rule

Note the subtle distinction with other responses this one is NOT assigning to a barename – it’s assigning to a list piece that just happens to be the entire list, thus changing the list contents in the exact same Python list object, instead of just reseating one reference (from past list object to new list object) like the other answers. Continue reading “How to remove things from a list while iterating?”