is there a better way?

snoe case.nelson at gmail.com
Fri Feb 10 13:08:24 EST 2006


markscala at gmail.com wrote:
> Problem:
>
> 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
> _____________________
>
> But this seems ugly to me, and using "while" give me the heebies.  Is
> there a better approach?
>
> hope this is clear.
> thanks


There's a few ways to do this, really depends on :

mylist = [1,2,3,4,5,6,0,0,0]

list comprehension (will get ALL non zeros, and strip out all zeros,
but is different from your function):
[x for x in mylist if x != 0]

list slice(same as your function):
mylist[:mylist.index(0)]

Depends what you want to happen if your list is something like:
[1,2,3,0,4,5,6,0,0]
[0,1,2,3,4,5,6]
[0,1,2,3,4,5,6,0]
[1,2,3,4,5,6]




More information about the Python-list mailing list