Remove elements as you traverse a list in Python [duplicate]
This question already has an answer here: How to remove items from a list while iterating? 26 answers 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(); }