[Python-ideas] proposed methods: list.replace / list.indices

Terry Reedy tjreedy at udel.edu
Sun Dec 30 11:46:45 CET 2012


On 12/29/2012 10:25 PM, David Kreuter wrote:

> I think it would be nice to have a method in 'list' to replace certain
> elements by others in-place. Like this:
>
>      l = [x, a, y, a]
>      l.replace(a, b)
>      assert l == [x, b, y, b]
>
> The alternatives are longer than they should be, imo. For example:
>
>      for i, n in enumerate(l):
>          if n == a:
>              l[i] = b

I dont see anything wrong with this. It is how I would do it in python. 
Wrap it in a function if you want. Or write it on two line ;-).

> If there is a reason not to add '.replace' as built-in method,

There is a perfectly good python version above that does the necessary 
search and replace as efficiently as possible. Thank you for posting it.

-- 
Terry Jan Reedy




More information about the Python-ideas mailing list