Deleting from a list

Emile van Sebille emile at fenx.com
Tue Jan 1 22:53:42 EST 2002


<bvdpoel at uniserve.com> wrote in message
news:3C326CF0.A28B9FC7 at uniserve.com...
>
> 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.
>
> I ired:
>
> for l in lines:
> if...:
> lines.remove(l)
>
> But, this buggers the sequence. If you have [1,2,3,6,6,6,7] and delete
> on the condition l==6, you only delete 2 '6's, not all 3.
>
> So, finally, I did:
>
> for i in len(lines)
> l=lines(i)
> ...
> if ..:
> lines[i]=None
>
> while(lines.count(None):
> lines.remove(None)
>
>
> My question: Is there a cleaner way to do all this? Having 2 loops seems
> to be ugly.
>

Deleting from a list while in a for loop can lead to trouble.  Doing it
yourself is safer:

>>> l = [1,2,3,6,6,6,7]
>>> i = 0
>>> while i < len(l):
 if l[i] == 6:
  del l[i]
 else:
  i += 1


>>> l
[1, 2, 3, 7]
>>>


Or you may want to consider something like:

>>> l = [1,2,3,6,6,6,7]
>>> [ i for i in l if i != 6]
[1, 2, 3, 7]


--

Emile van Sebille
emile at fenx.com

---------




More information about the Python-list mailing list