Better solution

holger krekel pyth at devel.trillke.net
Wed Aug 21 11:36:17 CEST 2002


Ken Seehof wrote:
> > Michael Hudson wrote:
> > > holger krekel <pyth at devel.trillke.net> writes:
> > > 
> > > > > 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.
> > > 
> > > It depends whether you want to change the acutal list object or merely
> > > have 'lst' refer to a changed list.  Bo was using .pop in his
> > > question, so it's possible he wanted the former.
> > 
> > But isn't 
> > 
> >     filter(None,lst) 
> > 
> > supposed to return a new list? 
> > 
> Yes, but that brand new list object is being copied into the target list,
> so the target list doesn't change it's identity.

Ok, i missed the requirement that the list-object identity 
should be preserved as it happens with

> >>> a = b = [1,2,3]
> >>> b[:] = [4,5,6]
> >>> a
> [4, 5, 6]

It does incur one more copy-operation instead of directly rebinding
a name to the temporary list created by filter(...).  This might
be harmful for large lists.

thanks for the explanation,

    holger




More information about the Python-list mailing list