Better solution

Michael Hudson mwh at python.net
Tue Aug 20 17:39:49 CEST 2002


"Mark McEahern" <marklists at mceahern.com> writes:

> > Well, I want to throw away a _same_ garbage from a list with less 
> > of coding.
> > This is current code, sure not the best ;-) Is any better solutions?
> > 
> > --------------8<------------------------
> > lst = ['', 'a', '', 'b', 'c', '', 'd']
> > map(lambda z:lst.pop(lst.index('')), range(0, lst.count('')))
> > --------------8<------------------------
> > 
> > Now lst equals to ['a', 'b', 'c', 'd'].
> 
> These would also do the trick and be less cryptic:
> 
>   filter(lambda x: x, lst)

Or equivalently filter(None, lst).

>   [x for x in lst if x]

If you want to mutate the list, I'd say:

lst[:] = filter(None, lst)

is better than the monstrosity above.

Cheers,
M.

-- 
  The ultimate laziness is not using Perl.  That saves you so much
  work you wouldn't believe it if you had never tried it.
                                        -- Erik Naggum, comp.lang.lisp



More information about the Python-list mailing list