for (String fruit : list) { if("banane".equals(fruit)) list.remove(fruit); System.out.println(fruit); }
Here a loop with remove instruction. At execution time, I get some ConcurrentModificationException, below the console output:
Exception in thread "main" java.util.ConcurrentModificationException at java.util.AbstractList$Itr.checkForComodification(AbstractList.java:449) at java.util.AbstractList$Itr.next(AbstractList.java:420) at Boucle.main(Boucle.java:14) abricot banane
Question: How to remove some element with a loop?
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.
The only way to remove duplicates with a single loop is with a hashset or equivalent. Sorting the list first also works, but technically sorting involves many loops. calloc a status bit array, check if previously found and mark off. If the next value exceeds the range, realloc and clear the new 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.
You need to use the iterator directly, and remove the item via that iterator.
for (Iterator<String> iterator = list.iterator(); iterator.hasNext(); ) { String fruit = iterator.next(); if ("banane".equals(fruit)) { iterator.remove(); } System.out.println(fruit); }
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