In Java I can do by using an Iterator
and then using the .remove()
method of the iterator to remove the last element returned by the iterator, like this:
import java.util.*;
public class ConcurrentMod {
public static void main(String[] args) {
List<String> colors = new ArrayList<String>(Arrays.asList("red", "green", "blue", "purple"));
for (Iterator<String> it = colors.iterator(); it.hasNext(); ) {
String color = it.next();
System.out.println(color);
if (color.equals("green"))
it.remove();
}
System.out.println("At the end, colors = " + colors);
}
}
/* Outputs:
red
green
blue
purple
At the end, colors = [red, blue, purple]
*/
How would I do this in Python? I can't modify the list while I iterate over it in a for loop because it causes stuff to be skipped (see here). And there doesn't seem to be an equivalent of the Iterator
interface of Java.
Using the groupby function, we can group the together occurring elements as one and can remove all the duplicates in succession and just let one element be in the list. This function can be used to keep the element and delete the successive elements with the use of slicing.
Best approach in Python is to make a new list, ideally in a listcomp, setting it as the [:]
of the old one, e.g.:
colors[:] = [c for c in colors if c != 'green']
NOT colors =
as some answers may suggest -- that only rebinds the name and will eventually leave some references to the old "body" dangling; colors[:] =
is MUCH better on all counts;-).
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