Better solution

holger krekel pyth at devel.trillke.net
Tue Aug 20 11:59:58 EDT 2002


Michael Hudson wrote:
> > > 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.

why the '[:]'? 

doesn't seem to make any difference here unless
filter is allowed to return the same lst-object.

    holger




More information about the Python-list mailing list