Removing items when moving a list in Python

In Java, I can do it using Iterator and then using .remove() to remove the last element returned by the iterator, for example:

 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 do I do this in Python? I cannot change the list while I iterate over it in a for loop, because it makes the material skip (see here ). And there seems to be no equivalent to the Iterator Java interface.

+10
python iterator list loops
Aug 30 '09 at 2:18
source share
4 answers

Go to the copy of the list:

 for c in colors[:]: if c == 'green': colors.remove(c) 
+18
Aug 30 '09 at 2:26
source share
— -

The best approach in Python is to create a new list, ideally in listcomp, setting it as [:] old one, for example:

 colors[:] = [c for c in colors if c != 'green'] 

NOT colors = , as some answers may give, it only retypes the name and ultimately leaves links to the old "body" that hangs; colors[:] = MUCH MORE in all counts; -).

+26
Aug 30 '09 at 2:26
source share

You can use the filter function:

 >>> colors=['red', 'green', 'blue', 'purple'] >>> filter(lambda color: color != 'green', colors) ['red', 'blue', 'purple'] >>> 
+4
Aug 30 '09 at 2:57
source share

or you can also do it

 >>> colors = ['red', 'green', 'blue', 'purple'] >>> if colors.__contains__('green'): ... colors.remove('green') 
0
Aug 30 '09 at 4:34
source share



All Articles