Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Buy a domain name - Register cheap domain names from $0.99 - Namecheap

Scalable Hosting That Grows With You

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Semrush - keyword research tool

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

39,938 questions

51,875 answers

573 users

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 7 hours ago by avibootz
...