Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: Removing list element while iterating over list [duplicate]

Tags:

python

list

I'm iterating over a list of elements in Python, do some action on it, and then remove them if they meet certain criteria.

for element in somelist:     do_action(element)     if check(element):         remove_element_from_list 

What should I use in place of remove_element? I have seen similar questions asked, but notice the presence of the do_action part that is to be executed for all elements and thus eliminates the solution of using filters.

like image 432
Scrontch Avatar asked May 16 '11 20:05

Scrontch


People also ask

How do you remove an element from a list while iterating in Python?

If you want to delete elements from a list while iterating, use a while-loop so you can alter the current index and end index after each deletion.

How do you remove duplicates from a list in a loop in Python?

You can make use of a for-loop that we will traverse the list of items to remove duplicates. The method unique() from Numpy module can help us remove duplicate from the list given. The Pandas module has a unique() method that will give us the unique elements from the list given.

Can we remove from list while iterating?

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

How do you remove duplicates from a list while keeping the same order of the elements?

If you want to preserve the order while you remove duplicate elements from List in Python, you can use the OrderedDict class from the collections module. More specifically, we can use OrderedDict. fromkeys(list) to obtain a dictionary having duplicate elements removed, while still maintaining order.


1 Answers

You could always iterate over a copy of the list, leaving you free to modify the original:

for item in list(somelist):   ...   somelist.remove(item) 
like image 175
bluepnume Avatar answered Oct 03 '22 23:10

bluepnume