[Tutor] list iteration [iteration and mutation?]
Karl Pflästerer
sigurd at 12move.de
Mon May 3 15:26:07 EDT 2004
On 3 May 2004, Magnus Lycka <- magnus at thinkware.se wrote:
[...]
> Here is a little study to display the phenomena in a simple case. Remove
> all strings in a list that start with 'm'.
[some approaches to delete items from a list]
> I think there are three lessons we can learn from this:
> 1. Modifying a list that we are iterating over is error prone.
> 2. Iterating backwards, from the end to the beginning, typically
> makes this problem go away.
> 3. Identifying objects by *what* they are, is often more robust
> that to identify them based on *where* they are.
Right. But there is a forth lesson to learn.
4. Try a functional approach. e.g.:
filter(lambda i: predicate(i), lst)
or
[i for i in lst if predicate(i)]
So with your example:
>>> filter(lambda s: not s.startswith('m'), l)
['polly', 'dolly', 'pike']
>>> [s for s in l if not s.startswith('m')]
['polly', 'dolly', 'pike']
Karl
--
Please do *not* send copies of replies to me.
I read the list
More information about the Tutor
mailing list