Python | Replace a sublist with another in the list

Method # 1: Using a loop (when a sublist is specified)
This method is used when we know the sublist to be replaced. We accomplish this task using loops and list slicing, and separate the logic for finding the indices that need to be manipulated first and then replaced.

# Python3 demo code work
# Replace the sublist with another in the list
# Using a loop (when a sublist is set)

 
# helper function for finding items

def find_sub_idx (test_list, repl_list, start = 0 ):

  length = len (repl_list) < / code>

for idx in range (start, len (test_list)):

if test_list [idx: idx + length] = = repl_list:

return idx, idx + length

 
# helper function for the final task

def replace_sub (test_list, repl_li st, new_list):

length = len (new_list)

idx = 0

for start, end in iter ( lambda : find_sub_idx (test_list, repl_list, idx), None ):

test_list [start: end] = new_list

idx = start + length

 
# initializing list

test_list = [ 4 , 5 , 6 , 7 , 10 , 2 ]

 
# print original list

print ( "The original list is:" + str (test_list))

  
# Replace list

repl_list = [ 5 , 6 , 7 ]

new_list = [ 11 , 1 ]

 
# Replace the sublist with another in the list
# Using a loop (when a sublist is specified)
replace_sub (test_list, repl_list, new_list)

 
# print result

print ( "List after replacing sublist:" + str (test_list))

Output:

 The original list is: [4, 5, 6, 7, 10, 2] List after replacing sublist: [4, 11, 1, 10 , 2] 

Method # 2: Using list slicing (when the sublist index is given)
This task becomes easier when we just need to replace the base sublist available start and end index, in which case slicing of the list is sufficient to achieve a solution to this problem.

# Python3 code to demonstrate how it works
# Replace the sublist with another in the list
# Use list slicing (when a sublist is specified squeak)

 
# initializing list

test_list = [ 4 , 5 , 6 , 7 , 10 , 2 ]

 
# print original list

print ( " The original list is: " + str (test_list))

  
# Replace sleep juice

repl_list_strt_idx = 1

repl_list_end_idx = 4

new_list = [ 11 , 1 ]

 
# Replace the sublist with another in the list
# Using list slicing (when a sublist index is specified)

test_list [repl_list_strt_idx: repl_list_end_idx] = new_list

 
# print result

print ( "List after replacing sublist:" + str (test_list))

Output:

 The original list is: [4, 5, 6, 7, 10, 2] List after replacing sublist: [4, 11, 1, 10, 2]