Add list.replace(old, new, /, count=-1) for in-place element replacement

Hi everyone! I wanted to propose adding an in-place list.replace(old, new, /, count=-1) method to list and UserList.

Right now, if we want to replace matching elements inside a list in place without allocating a temporary list via lst[:] = [...], we either write a manual enumerate loop or scan the list twice to avoid ValueError from list.index().

# Example

## Loop then check
if old in key_list:
    key_list[key_list.index(old)] = new

## My proposed list.replace():
key_list.replace(old, new, count=1)

This proposed .replace() mutates the list in place, returns None, and compares single top-level elements (self[i] is old or self[i] == old). And like str.replace(), it is a no-op when old is not found and uses count=-1 to support replacing either all matches or the first count matches.

What do you all think?

I think using enumerate is just fine to me

1 Like

What’s wrong with using enumerate, for example?

def list_replace(xs, old, new, count=-1):
    if count < 0:
        count = len(xs)
    cnt = 0
    for idx, elt in enumerate(xs):
        if elt == old:
            if cnt < count:
                xs[idx] = new
                cnt += 1
            else:
                break

Or you can scan list to get indices of matched elements and then go over this set of indices to do replace. No need to scan list twice or catch exceptions…

People also could use other data types than list, e.g. ndarray’s:

>>> import numpy as np
>>> a = np.array([1, 2, 3, 2, 10, 11, 2, 15])
>>> a[np.where(a == 2)[0]] = 123  # replace all
>>> a
array([  1, 123,   3, 123,  10,  11, 123,  15])
>>> a[np.where(a == 123)[0][:2]] = 2  # at most two
>>> a
array([  1,   2,   3,   2,  10,  11, 123,  15])

when one-liners with temporary list are too expensive.

Note, that your proposal is not like str.replace(), which replaces substrings rather than characters. Remember, that list('abc') is ['a', 'b', 'c']. To match this behavior, probably your method should rather replace sublists, e.g. [1, 2, 3].replace([1, 2], [4]) -> [4, 3].

Please take look on Suggesting new features and language changes. It’s not clear, especially, what benefits this brings to Python users. Is this something occurring in applications, can you show examples in real-world code?

1 Like

oh right, thanks!

1 Like

Nothing is wrong with using enumerate exactly, and that is also my go-to.

It just occurred to me why .replace() does not exist on lists, kind of like a built-in thing.

Thanks for the feedback! I will definitely look more into Suggesting new features and language changes too.

1 Like

I’d say what’s wrong with yours is that it doesn’t stop when it should.

For example for list_replace([1,2,3,4,5], 1, 0, count=1), you replace the 1, and then you still go through the rest of the list despite not being allowed another replacing, and despite your code having a break indicating that you do want to stop early.

(Also, the OP already pointed out (self[i] is old or self[i] == old) and yours is missing that is check.)

1 Like

If those cases are handled with the traditional enumerate and other workarounds, do you think a .replace() method on lists still makes sense?

Or the third option again:

key_list.append(old)
key_list[key_list.index(old)] = new
key_list.pop()

As other have mentioned, there are perfectly suitable existing solutions; for example, using enumerate. That being said, how often do you need to replace an element in a list? Every time a new method is introduced, it imposes a burden on Python developers, to implement, test, and maintain the code, on documentation writers, to add to the official documentation, on translators, who work on making available Python’s documentation in languages other than English, on tutorial writers, etc. The motivation for adding new functions or methods has to be more than just “thinking about it”.

4 Likes

right, thanks!