Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to remove items from a list while iterating?

I'm iterating over a list of tuples in Python, and am attempting to remove them if they meet certain criteria.

for tup in somelist:     if determine(tup):          code_to_remove_tup 

What should I use in place of code_to_remove_tup? I can't figure out how to remove the item in this fashion.

like image 590
lfaraone Avatar asked Jul 30 '09 15:07

lfaraone


People also ask

Can we remove element from list while iterating?

Even though java. util. ArrayList provides the remove() methods, like remove (int index) and remove (Object element), you cannot use them to remove items while iterating over ArrayList in Java because they will throw ConcurrentModificationException if called during iteration.

Can you remove item from list while iterating Python?

We can delete multiple elements from a list while iterating, but we need to make sure that we are not invalidating the iterator. So either we need to create a copy of the list for iteration and then delete elements from the original list, or we can use the list comprehension or filter() function to do the same.

Can I remove element from list while iterating Java?

In Java 8, we can use the Collection#removeIf API to remove items from a List while iterating it.

How would you remove elements from a Collection during iteration?

An element can be removed from a Collection using the Iterator method remove(). This method removes the current element in the Collection. If the remove() method is not preceded by the next() method, then the exception IllegalStateException is thrown.


1 Answers

You can use a list comprehension to create a new list containing only the elements you don't want to remove:

somelist = [x for x in somelist if not determine(x)] 

Or, by assigning to the slice somelist[:], you can mutate the existing list to contain only the items you want:

somelist[:] = [x for x in somelist if not determine(x)] 

This approach could be useful if there are other references to somelist that need to reflect the changes.

Instead of a comprehension, you could also use itertools. In Python 2:

from itertools import ifilterfalse somelist[:] = ifilterfalse(determine, somelist) 

Or in Python 3:

from itertools import filterfalse somelist[:] = filterfalse(determine, somelist) 
like image 188
David Raznick Avatar answered Sep 28 '22 08:09

David Raznick