Berteun Damman <[EMAIL PROTECTED]> wrote: > On Tue, 29 Jan 2008 09:23:16 -0800 (PST), [EMAIL PROTECTED] ><[EMAIL PROTECTED]> wrote: >> If you're going to delete elements from >> a list while iterating over it, then do >> it in reverse order: > > Why so hard? Reversing it that way creates a copy, so you might as > well do: >>>> a = [ 98, 99, 100 ] >>>> for i, x in enumerate(a[:]): > ... if x == 99: del(a[i]) > ... print x
Why so hard? >>> a = [ 98, 99, 100, 98, 99, 100 ] >>> for i, x in enumerate(a[:]): if x == 99: del(a[i]) >>> a [98, 100, 98, 99] oops! But: >>> a = [ 98, 99, 100, 98, 99, 100 ] >>> last_idx = len(a) - 1 >>> for i, x in enumerate(a[::-1]): if x == 99: del(a[last_idx - i]) >>> a [98, 100, 98, 100] Reversing it works. Your code doesn't. -- http://mail.python.org/mailman/listinfo/python-list