is there a better way?
Tim Chase
python.list at tim.thechases.com
Fri Feb 10 13:12:42 EST 2006
> You have a list of unknown length, such as this: list =
> [X,X,X,O,O,O,O]. You want to extract all and only the X's. You know
> the X's are all up front and you know that the item after the last X is
> an O, or that the list ends with an X. There are never O's between
> X's.
>
> I have been using something like this:
> _____________________
>
> while list[0] != O:
> storage.append(list[0])
> list.pop(0)
> if len(list) == 0:
> break
> _____________________
While it doesn't modify your list, you can try something like
storage = [q for q in myList if q != O]
If you've already got stuff in storage that you want to keep, you
can use
storage.extend([q for q in myList if q != O])
I suppose, if you wanted to remove all the O's, you could then
just do
myList = [q for q in myList if q == O]
(trickiness using Oh's vs. using zeros...)
-tkc
More information about the Python-list
mailing list