Deleting from a list (reprise)
Emile van Sebille
emile at fenx.com
Wed Jan 2 14:50:52 EST 2002
"Jason Orendorff" <jason at jorendorff.com> wrote in message
news:mailman.1009995124.12967.python-list at python.org...
> > def delwhile(sequence, marker):
> > sequence[:] = sequence
> > while marker in sequence: sequence.remove(marker)
>
> I think you mean
> sequence = sequence[:] # make a copy of 'sequence'
>
> What you wrote splices the list into itself (basically a no-op),
> with the result that the original sequence is modified in-place.
> The other runs, therefore, work with freqma=0.
>
> Also: try this one. It's pretty quick.
>
> def delcomp(sequence, marker):
> sequence = [i for i in sequence if i != marker]
>
This doesn't modify sequence, but creates a new one within the function.
It'll work if you add 'return sequence' and invoke it as
sequence=delcomp(sequence,marker)
Alternately, this combination of the two modifies sequence:
>>> seq
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> def delcomp(sequence, marker):
sequence[:] = [i for i in sequence if i != marker]
>>> seq
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> delcomp(seq,3)
>>> seq
[0, 1, 2, 4, 5, 6, 7, 8, 9]
>>>
--
Emile van Sebille
emile at fenx.com
---------
More information about the Python-list
mailing list