is there a better way?

Paul Rubin http
Sat Feb 11 02:18:35 EST 2006


"markscala at gmail.com" <markscala at gmail.com> writes:
> But this seems ugly to me, and using "while" give me the heebies.  Is
> there a better approach?

Note that "list" is the name of a built-in type; I used "mylist".
Alex Martelli described how to do it in log n time using the bisect
module.  Here's a dumb linear time method that might be faster for
small n (of course you should time the different methods for your
particular Python implementation, if the speed matters):

   del mylist[len(mylist) - mylist.count(0):]

The above an example of where the natural

   del mylist[-mylist.count(0):]

does totally the wrong thing if there are no 0's in the list.  There
was a huge thread a while back about ways to fix that.

Another way, might be faster, esp. there's more than a few 0's:

   try:
     del mylist[mylist.index(0)]
   except ValueError: 
     pass   # no 0's in the list



More information about the Python-list mailing list