No, I'm afraid there is no built-in function that does this, however you can create your own!
The steps are really easy, we just need to slide a window over the list where the width of the window is the len(old)
. At each position, we check if the window ==
to old
and if it is, we slice before the window, insert new
and concatenate the rest of the list
on after - this can be done simply be assigning directly to the old
slice as pointed out by @OmarEinea
.
def replace(seq, old, new):
seq = seq[:]
w = len(old)
i = 0
while i < len(seq) - w + 1:
if seq[i:i+w] == old:
seq[i:i+w] = new
i += len(new)
else:
i += 1
return seq
and some tests show it works:
>>> replace([0, 1, 3], [0, 1], [1, 2])
[1, 2, 3]
>>> replace([0, 1, 3, 0], [0, 1], [1, 2])
[1, 2, 3, 0]
>>> replace([0, 1, 3, 0, 1], [0, 1], [7, 8])
[7, 8, 3, 7, 8]
>>> replace([1, 2, 3, 4, 5], [1, 2, 3], [1, 1, 2, 3])
[1, 1, 2, 3, 4, 5]
>>> replace([1, 2, 1, 2], [1, 2], [3])
[3, 3]
As pointed out by @user2357112
, using a for-loop
leads to re-evaluating replaced sections of the list
, so I updated the answer to use a while
instead.