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.
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.
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.
In Java 8, we can use the Collection#removeIf API to remove items from a List while iterating it.
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.
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With