How to replace all occurrences of a sublist with new list in Python

1 Answer

0 votes
def replace_all_sublists(lst, old, new):
    result = []
    i = 0
    n = len(old)

    while i < len(lst):
        if lst[i:i+n] == old:
            result.extend(new)
            i += n
        else:
            result.append(lst[i])
            i += 1

    return result

lst = [1, 2, 3, 4, 7, 3, 4, 5]
print(replace_all_sublists(lst, [3, 4], ["x", "y"]))



'''
run:

[1, 2, 'x', 'y', 7, 'x', 'y', 5]

'''

 



answered Feb 14 by avibootz
...