[Python-ideas] proposed methods: list.replace / list.indices
David Kreuter
dkreuter at gmail.com
Sun Dec 30 04:25:38 CET 2012
Hi python-ideas.
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
Or:
l = [b if n==a else n for n in l]
And this is what happens when someone tries to "optimize" this process.
It totally obscures the intention:
try:
i = 0
while i < len(l):
i = l.index(a, i)
l[i] = b
i += 1
except ValueError:
pass
If there is a reason not to add '.replace' as built-in method, it could be
implemented in pure python efficiently if python provided a version of
'.index' that returns the index of more than just the first occurrence of a
given item. Like this:
l = [x, a, b, a]
for i in l.indices(a):
l[i] = b
So adding .replace and/or .indices… Good idea? Bad idea?
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-ideas/attachments/20121230/1b67ec8b/attachment.html>
More information about the Python-ideas
mailing list