Python | Replace sublist with other in list
Last Updated :
02 Jun, 2023
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
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
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
test_list = [ 4 , 5 , 6 , 7 , 10 , 2 ]
print ( "The original list is : " + str (test_list))
repl_list = [ 5 , 6 , 7 ]
new_list = [ 11 , 1 ]
replace_sub(test_list, repl_list, new_list)
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
test_list = [ 4 , 5 , 6 , 7 , 10 , 2 ]
print ( "The original list is : " + str (test_list))
repl_list_strt_idx = 1
repl_list_end_idx = 4
new_list = [ 11 , 1 ]
test_list[repl_list_strt_idx : repl_list_end_idx] = new_list
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
test_list = [ 4 , 5 , 6 , 7 , 10 , 2 ]
print ( "The original list is : " + str (test_list))
repl_list = [ 5 , 6 , 7 ]
new_list = [ 11 , 1 ]
test_list_str = "," .join( str (i) for i in test_list)
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)
test_list = [ int (i) for i in test_list_str.split( "," )]
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#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
test_list = [ 4 , 5 , 6 , 7 , 10 , 2 ]
print ( "The original list is : " + str (test_list))
repl_list = [ 5 , 6 , 7 ]
new_list = [ 11 , 1 ]
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
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
test_list = [ 4 , 5 , 6 , 7 , 10 , 2 ]
print ( "The original list is: " + str (test_list))
repl_list = [ 5 , 6 , 7 ]
new_list = [ 11 , 1 ]
try :
idx = test_list.index(repl_list[ 0 ])
test_list[idx:idx + len (repl_list)] = new_list
except ValueError:
pass
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:
- Initialize the list to be modified and the sublist to be replaced with new values.
- Use the built-in function reduce to iterate through each element in the original list.
- For each iteration, check if the sublist to be replaced matches with the current slice of the original list.
- If the sublist matches, append the index of the current slice to a list.
- After all iterations, replace the sublist with the new values using the indices from the previous step.
- Return the modified list.
Python3
from functools import reduce
test_list = [ 4 , 5 , 6 , 7 , 10 , 2 ]
print ( "The original list is : " + str (test_list))
repl_list = [ 5 , 6 , 7 ]
new_list = [ 11 , 1 ]
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
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 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:
- Initialize the list test_list.
- Print the original list test_list.
- Define the starting and ending index of the sublist to be replaced, and the new list to replace the sublist with.
- 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.
- Use the itertools.chain() method to concatenate the three slices into a single iterable.
- Convert the iterable back into a list using the list() method.
- Print the resulting list.
Python3
import itertools
test_list = [ 4 , 5 , 6 , 7 , 10 , 2 ]
print ( "The original list is : " + str (test_list))
repl_list_strt_idx = 1
repl_list_end_idx = 4
new_list = [ 11 , 1 ]
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))
)
test_list = list (test_list)
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 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`.
Similar Reads
Print All Sublists of a List in Python
We are given a list and our task is to generate all possible sublists (continuous or non-continuous subsequences). For example: a = [1, 2, 3] The possible sublists are: [[], [1], [2], [3], [1, 2], [2, 3], [1, 3], [1, 2, 3]] Using itertools.combinationsitertools.combinations() generates all possible
3 min read
Python | Linear search on list or tuples
Let us see a basic linear search operation on Python lists and tuples. A simple approach is to do a linear search, that is Start from the leftmost element of the list and one by one compare x with each element of the list.If x matches with an element, return True.If x doesnât match with any of the e
2 min read
replace() in Python to replace a substring
replace() method in Python allows us to replace a specific part of a string with a new value. It returns a new string with the change without modifying the original one. We can also specify how many times the replacement should occur. For Example: [GFGTABS] Python s = "hlo AB world" # Repl
2 min read
Remove All Sublists Outside the Given Range - Python
The problem "Remove All Sublists Outside the Given Range" involves filtering out sublists from a list of lists based on a specified range. Each sublist is assessed and only those where all elements fall within the given range (e.g., between low and high) are kept. We are given a matrix m= m = [[1, 2
3 min read
How to Replace Values in a List in Python?
Replacing values in a list in Python can be done by accessing specific indexes and using loops. In this article, we are going to see how to replace the value in a List using Python. We can replace values in the list in several ways. The simplest way to replace values in a list in Python is by using
2 min read
Python | Pandas Series.replace()
Pandas series is a One-dimensional ndarray with axis labels. The labels need not be unique but must be a hashable type. The object supports both integer- and label-based indexing and provides a host of methods for performing operations involving the index. Pandas Series.replace() function is used to
3 min read
Pandas Replace Multiple Values in Python
Replacing multiple values in a Pandas DataFrame or Series is a common operation in data manipulation tasks. Pandas provides several versatile methods for achieving this, allowing you to seamlessly replace specific values with desired alternatives. In this context, we will explore various approaches
5 min read
Update List in Python
In Python Programming, a list is a sequence of a data structure that is mutable. This means that the elements of a list can be modified to add, delete, or update the values. In this article we will explore various ways to update the list. Let us see a simple example of updating a list in Python. [GF
3 min read
Python - Replace all occurrences of a substring in a string
Replacing all occurrences of a substring in a string means identifying every instance of a specific sequence of characters within a string and substituting it with another sequence of characters. Using replace()replace () method is the most straightforward and efficient way to replace all occurrence
2 min read
How to replace a word in excel using Python?
Excel is a very useful tool where we can have the data in the format of rows and columns. We can say that before the database comes into existence, excel played an important role in the storage of data. Nowadays using Excel input, many batch processing is getting done. There may be the requirement o
3 min read