Open In App

Python | Replace sublist with other in list

Improve
Improve
Like Article
Like
Save
Share
Report

Sometimes, while working with Python, we can have a problem in which we need to manipulate a list in such a way that we need to replace a sublist with another. This kind of problem is common in the web development domain. Let’s discuss certain ways in which this task can be performed. 

Method #1 : Using loop ( When sublist is given ) This method is employed in cases we know the sublist which is to be replaced. We perform this task using loops and list slicing and divide the logic of finding the indices which need to be manipulated first and then perform the replacement. 

Python3




# Python3 code to demonstrate working of
# Replace sublist with other in list
# Using loop (when sublist is given)
 
# helper function to find elements
def find_sub_idx(test_list, repl_list, start = 0):
    length = len(repl_list)
    for idx in range(start, len(test_list)):
        if test_list[idx : idx + length] == repl_list:
            return idx, idx + length
 
# helper function to perform final task
def replace_sub(test_list, repl_list, 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]
 
# printing original list
print("The original list is : " + str(test_list))
 
# Replace list
repl_list = [5, 6, 7]
new_list = [11, 1]
 
# Replace sublist with other in list
# Using loop (when sublist is given)
replace_sub(test_list, repl_list, new_list)
 
# printing 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]

Time Complexity: O(n)
Auxiliary Space: O(n)

  Method #2 : Using list slicing ( When sublist index is given ) This task becomes easier when we just need to replace a sublist basic on the start and ending index available and list slicing is sufficient in such cases to achieve solution to this problem. 

Python3




# Python3 code to demonstrate working of
# Replace sublist with other in list
# Using list slicing ( When sublist index is given )
 
# initializing list
test_list = [4, 5, 6, 7, 10, 2]
 
# printing original list
print("The original list is : " + str(test_list))
 
# Replace list
repl_list_strt_idx = 1
repl_list_end_idx = 4
new_list = [11, 1]
 
# Replace sublist with other in list
# Using list slicing ( When sublist index is given )
test_list[repl_list_strt_idx : repl_list_end_idx] = new_list
 
# printing 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]

Time Complexity: O(n) where n is the number of elements in the list “test_list”.  
Auxiliary Space: O(n), where n is the number of elements in the new list 

Method #3 : Using re.sub() (Regular Expression)
This method utilizes regular expression module to find the sublist in the list and replace it with the new sublist. This method is useful when the sublist to be replaced is not known but it can be described using regular expressions.

Python3




import re
 
# initializing list
test_list = [4, 5, 6, 7, 10, 2]
 
# printing original list
print("The original list is : " + str(test_list))
 
# Replace list
repl_list = [5, 6, 7]
new_list = [11, 1]
 
# join the list elements with ","
test_list_str = ",".join(str(i) for i in test_list)
 
# Replace sublist with other in list
# Using re.sub()
repl_list_str = ",".join(str(i) for i in repl_list)
new_list_str = ",".join(str(i) for i in new_list)
test_list_str = re.sub(repl_list_str, new_list_str, test_list_str)
 
# convert the modified string back to list
test_list = [int(i) for i in test_list_str.split(",")]
 
# printing result
print("List after replacing sublist : " + str(test_list))
#This code is contributed by Edula Vinay Kumar Reddy


Output

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

Time complexity: O(n)

Auxiliary Space: O(n)

Method#4 using list comprehension

Step-by-step algorithm:

Initialize a list named idx to store the starting indices of the sublist to be replaced.
Traverse the list using a for loop and check if the sublist starting from the current index is equal to the given sublist.
If the sublist is found, append the starting index to the idx list.
Traverse the idx list using a for loop and replace the sublist at each starting index with the new list.
Print the updated list.

Python3




# Initializing list
test_list = [4, 5, 6, 7, 10, 2]
 
# printing original list
print("The original list is : " + str(test_list))
 
# Replace list
repl_list = [5, 6, 7]
new_list = [11, 1]
 
# Replace sublist with other in list
idx = [i for i in range(len(test_list)) if test_list[i:i+len(repl_list)] == repl_list]
for i in range(len(idx)):
    test_list[idx[i]:idx[i]+len(repl_list)] = new_list
 
# printing 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]

Time complexity:
The time complexity of this approach is O(n*m), where n is the length of the input list and m is the length of the sublist to be replaced. This is because we traverse the list once to find the starting indices of the sublist and then traverse the idx list once to replace the sublist with the new list.

Auxiliary space:
The auxiliary space complexity of this approach is O(k), where k is the number of occurrences of the sublist to be replaced in the input list. This is because we store the starting indices of the sublist in the idx list, which can have a maximum length of k. The space required to store the new list is constant and does not depend on the input size.

Method #5: Using built-in list methods

Use built-in list methods like index() and slice() to find the index of the sublist and replace it with the new list.

Python3




# initializing list
test_list = [4, 5, 6, 7, 10, 2]
 
# printing original list
print("The original list is: " + str(test_list))
 
# Replace list
repl_list = [5, 6, 7]
new_list = [11, 1]
 
# Using built-in list methods
try:
    idx = test_list.index(repl_list[0])
    test_list[idx:idx+len(repl_list)] = new_list
except ValueError:
    pass
 
# printing 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]

Time complexity: O(n), where n is the length of the list,”
Auxiliary space: O(1), as it does not require any additional data structures.

Method #6:Using reduce

Algorithm:

  1. Initialize the list to be modified and the sublist to be replaced with new values.
  2. Use the built-in function reduce to iterate through each element in the original list.
  3. For each iteration, check if the sublist to be replaced matches with the current slice of the original list.
  4. If the sublist matches, append the index of the current slice to a list.
  5. After all iterations, replace the sublist with the new values using the indices from the previous step.
  6. Return the modified list.

Python3




from functools import reduce
 
#Initializing list
test_list = [4, 5, 6, 7, 10, 2]
 
#printing original list
print("The original list is : " + str(test_list))
 
#Replace list
repl_list = [5, 6, 7]
new_list = [11, 1]
 
#Replace sublist with other in list using reduce
idx = reduce(lambda x, y: x + [y] if test_list[y:y+len(repl_list)] == repl_list else x, range(len(test_list)), [])
 
for i in range(len(idx)):
    test_list[idx[i]:idx[i]+len(repl_list)] = new_list
 
#printing result
print("List after replacing sublist : " + str(test_list))
#This code is contributed by Vinay Pinjala.


Output

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

Time Complexity: The time complexity of this implementation is O(n), where n is the length of the original list. The reduce function iterates through each element in the original list only once.

Auxiliary Space: The space complexity of this implementation is O(n), where n is the length of the original list. The space required to store the list of indices where the sublist matches is proportional to the length of the original list.

Method #7: Using itertools:

Algorithm:

  1. Initialize the list test_list.
  2. Print the original list test_list.
  3. Define the starting and ending index of the sublist to be replaced, and the new list to replace the sublist with.
  4. Use the itertools.islice() method to slice the list into three parts: the elements before the starting index, the new list to replace the sublist with, and the elements after the ending index.
  5. Use the itertools.chain() method to concatenate the three slices into a single iterable.
  6. Convert the iterable back into a list using the list() method.
  7. Print the resulting list.

Python3




import itertools
 
# initializing list
test_list = [4, 5, 6, 7, 10, 2]
 
# printing original list
print("The original list is : " + str(test_list))
 
# Replace list
repl_list_strt_idx = 1
repl_list_end_idx = 4
new_list = [11, 1]
 
# Replace sublist with other in list
# Using itertools.islice()
test_list = itertools.chain(
itertools.islice(test_list, 0, repl_list_strt_idx),
new_list,
itertools.islice(test_list, repl_list_end_idx, len(test_list))
)
 
# convert the chain object back to a list
test_list = list(test_list)
 
# printing result
print("List after replacing sublist : " + str(test_list))
#This code is contributed by Rayudu.


Output

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

Time complexity: The time complexity of slicing a list using itertools.islice() is O(k), where k is the length of the slice. Concatenating the slices using itertools.chain() takes O(1) time, and converting the iterable back into a list using list() takes O(n) time, where n is the length of the original list. Therefore, the overall time complexity of the algorithm is O(n).

Auxiliary Space: The space complexity of the algorithm is O(n), as we create a new list of size n to store the concatenated slices. The itertools methods used in the algorithm are lazy and do not create any new data structures, so they do not contribute to the space complexity.
 

Method#8: Using Recursive method.

1. Check if `start` index is greater than or equal to the length of the remaining `test_list` minus the length of `repl_list` plus one. If true, then return.
2. Check if `repl_list` exists in `test_list` starting from index `start`. If true, replace the sublist with `new_list` and update `start` to the end of `new_list`.
3. Otherwise, increment `start` by 1 and call the function recursively with the updated `start` index.
4. Repeat until all occurrences of `repl_list` have been replaced in `test_list`.

Python3




def replace_sub_recursive(test_list, repl_list, new_list, start=0):
    if start >= len(test_list) - len(repl_list) + 1:
        return
    if test_list[start:start+len(repl_list)] == repl_list:
        test_list[start:start+len(repl_list)] = new_list
        start += len(new_list)
    else:
        start += 1
    replace_sub_recursive(test_list, repl_list, new_list, start)
test_list = [4, 5, 6, 7, 10, 2]
repl_list = [5, 6, 7]
new_list = [11, 1]
replace_sub_recursive(test_list, repl_list, new_list)
print("List after replacing sublist : " + str(test_list))


Output

List after replacing sublist : [4, 11, 1, 10, 2]

Time Complexity:
The worst-case time complexity of the function is O(n^2), where n is the length of `test_list`. This occurs when `repl_list` occurs in `test_list` at every possible position, and `new_list` is shorter than `repl_list`. In each recursive call, the function checks a sublist of `test_list` of length `len(repl_list)` for equality with `repl_list`, and this operation takes O(len(repl_list)). Therefore, the worst-case time complexity is O(n * len(repl_list)).

Space Complexity:
The function has a space complexity of O(1) since it updates the input list `test_list` in place and only uses a constant amount of additional memory for the variables `repl_list`, `new_list`, and `start`.



Last Updated : 02 Jun, 2023
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads