Most efficient solution?

Alex Martelli aleaxit at yahoo.com
Mon Jul 16 12:03:27 EDT 2001


"Jay Parlar" <jparlar at home.com> wrote in message
news:mailman.995289809.28477.python-list at python.org...
    ...
> for eachItem in A:
>     if eachItem in B:
>         A.remove(eachItem)
>
> Now, this will work fine,

Are you sure about that?  Normally, modifying the list
you're iterating on does NOT work fine.  Have you tested
a decent variety of cases?  For example:

>>> a=['ciao']*7
>>> for x in a: a.remove(x)
...
>>> a
['ciao', 'ciao', 'ciao']
>>>

as you see, NOT all seven occurrences of 'ciao' have
been removed.  Before worrying about speed, I would
suggest you first make sure your code is CORRECT... I
think this loop will misbehave if any two successive
items of A are both in B (only the first one will be
removed).  Are you sure this can't occur...?


Alex






More information about the Python-list mailing list