Deleting from a list

bvdpoel at uniserve.com bvdpoel at uniserve.com
Wed Jan 2 11:39:18 EST 2002


Thanks for all the suggestions guys! I think that walking the list
backwards probably makes my life the easiest...

Hans Nowak wrote:
> 
> bvdpoel at uniserve.com wrote:
> >
> > Does python have a notion as to where the current item in a list is? I
> > have something like:
> >
> >         for l in lines:
> >                 if something ...
> >                 if something else:
> >                         delete l from list
> >
> > Of course, this doesn't work. So, I tried:
> >
> >         for i in len(lines):
> >                 l=lines[i]
> >                 ...
> >                 if ...:
> >                         lines.pop(i)
> >
> > and this causes problems since 'i' can now point to out of range lines.
> 
> You can traverse the list backwards:
> 
> >>> x = [1, 2, 3, 6, 7, 8, 1, 1, 7, 1]
> >>> for i in range(len(x)-1,-1,-1):
>         if x[i] == 1:  # or a condition of your choice
>                 del x[i]
> >>> x
> [2, 3, 6, 7, 8, 7]
> >>>
> 
> HTH,
> 
> --Hans (base64.decodestring('d3VybXlAZWFydGhsaW5rLm5ldA==\n')
>        # decode for email address ;-)
> Site:: http://www.awaretek.com/nowak/

-- 
Bob van der Poel ** Wynndel, British Columbia, CANADA **
EMAIL: bvdpoel at uniserve.com
WWW:   http://users.uniserve.com/~bvdpoel



More information about the Python-list mailing list