fork download
  1. import itertools
  2.  
  3. def find_sublists(seq, sublist):
  4. length = len(sublist)
  5. for index, value in enumerate(seq):
  6. if value == sublist[0] and seq[index:index+length] == sublist:
  7. yield index, index+length
  8.  
  9. def replace_sublist(seq, target, replacement, maxreplace=None):
  10. sublists = list(find_sublists(seq, target))
  11. if maxreplace:
  12. sublists = itertools.islice(sublists, maxreplace)
  13. for start, end in sublists:
  14. seq[start:end] = replacement
  15.  
  16. seq = list('banana')
  17. target = list('ban')
  18. replacement = list('taxicab')
  19.  
  20. replace_sublist(seq, target, replacement)
  21.  
  22. print(seq)
Success #stdin #stdout 0.04s 9384KB
stdin
Standard input is empty
stdout
['t', 'a', 'x', 'i', 'c', 'a', 'b', 'a', 'n', 'a']