Better way to replace/remove characters in a list of strings.

George Sakkis george.sakkis at gmail.com
Tue Sep 5 19:03:00 EDT 2006


Chris Brat wrote:

> Hi
>
> Wouldn't this only cause problems with large lists - for once off
> scripts with small lists it doesn't seem like a big issue to me.
>
> Regards,
> Chris
>
> Bruno Desthuilliers wrote:
> > Chris Brat a écrit :
> > > Thanks, thats exactly what I was looking for - very neat.
> > >
> > Just note that both solutions rebind the name to a newly constructed
> > list instead of modifying the original list in place. This is usually
> > the RightThing(tm), but sometimes one wants an in-place modification.


The extra memory to allocate the new list is usually a minor issue; the
important one is correctness, if the original list is referenced by
more than one names. Check the following almost identical-looking
cases:
1)
>>> x = ["abbbb","123a","nnnnas"]
>>> y = x
>>> x = [s.replace('a', 'b') for s in x]   # rebind to new list
>>> y is x
False

2)
>>> x = ["abbbb","123a","nnnnas"]
>>> y = x
>>> x[:] = [s.replace('a', 'b') for s in x]  # in place modification
>>> y is x
True

Neither case is always "the correct"; correctness depends on the
problem at hand, so you should know the difference and decide between
rebinding and mutation accordingly.

George




More information about the Python-list mailing list