On Jan 29, 8:17 pm, Duncan Booth <[EMAIL PROTECTED]> wrote: > 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])
Why so hard? :) a = [x for x in a if x != 99] OK, so this doesn't modify a in place.. but how often do you really need to do that? If I really had to modify it in place (and the condition wasn't really x == 99), how about: bad_indices = [i for i, x in enumerate(a) if x == 99] for bad_index in reversed(bad_indices): del a[bad_index] -- Paul Hankin -- http://mail.python.org/mailman/listinfo/python-list