Most efficient solution?

Jay Parlar jparlar at home.com
Mon Jul 16 16:27:28 EDT 2001


> > 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...?

Hmm... That's very interesting. Well, I guess you learn something new every day ;-) I suppose the simple solution (to my 
original code) is to place all non-offending items in a new list, ie. 

>>> for eachItem in a:
... 	if each not in b:
... 		final.append(eachItem)
... 

I've never noticed the list behaviour before that you pointed out, what causes that, if you don't mind my asking?

I also want to take this chance to really thank everyone for the wealth of replies to this topic. That's what I love about this 
list, find an interesting enough question (which I guess this one is) and everyone throws themselves at it.


Jay Parlar

PS. (If this messages shows up on the list a bunch of times, please forgive me, my e-mail client is acting a little strangely)

----------------------------------------------------------------
Software Engineering III
McMaster University
Hamilton, Ontario, Canada

"Though there are many paths
At the foot of the mountain
All those who reach the top
See the same moon."







More information about the Python-list mailing list