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?