Removing items from a list in a loop

Greg Ewing greg at cosc.canterbury.ac.nz
Sun Jun 25 22:21:20 EDT 2000


Andrew Henshaw wrote:
> 
> >Is there a safe way to iterate through a list and remove some items?

I sometimes do it this way:

  i = 0
  while i < len(l):
    if f(l[i]):
      del l[i]
    else:
      i = i + 1

-- 
Greg Ewing, Computer Science Dept,
+--------------------------------------+
University of Canterbury,	   | A citizen of NewZealandCorp, a	  |
Christchurch, New Zealand	   | wholly-owned subsidiary of USA Inc.  |
greg at cosc.canterbury.ac.nz	   +--------------------------------------+



More information about the Python-list mailing list