list comparison help?

mik3l3374 at gmail.com mik3l3374 at gmail.com
Sat Apr 14 06:51:06 EDT 2007


On Apr 14, 5:36 pm, "Dropkick Punt" <notrealaddr... at all.com> wrote:
> Hi. I have a list of common prefixes:
>
> >>> prefixes = [ "the", "this", "that", "da", "d", "is", "are", "r", "you", "u"]
>
> And I have a string, that I split() into a list.
>
> >>> sentence = "what the blazes is this"
> >>> sentence = sentence.split()
>
> Now I want to strip the sentence of all words in the prefix list.
>
> I tried this method:
>
> >>> for x in prefixes:
>
> ...       if sentence.index(x):
> ...             del sentence[sentence.index(x)]
>
> This raises, the error:
>
> Traceback (most recent call last):
>   File "<stdin>", line 3, in ?
> ValueError: list.index(x): x not in list
>
> This puzzles me, because if x isn't in the list, the subroutine shouldn't attempt to delete it
> from the list, so I'm not sure why it's complaining.
>
> Can anybody explain this to me, &/or show me a better way to do it?

>>> prefixes = [ "the", "this", "that", "da", "d", "is", "are", "r", "you", "u"]
>>> sentence = "what the blazes is this"
>>> sentence = sentence.split()
>>> sentence
['what', 'the', 'blazes', 'is', 'this']
>>> set(sentence).difference(prefixes)
set(['what', 'blazes'])




More information about the Python-list mailing list