Deleting from a list
Hans Nowak
wurmy at earthlink.net
Tue Jan 1 23:13:24 EST 2002
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/
More information about the Python-list
mailing list