Python – Replace sublist from Initial element
Last Updated :
09 Apr, 2023
Given a list and replacement sublist, perform the replacement of list sublist on basis of initial element of replacement sublist.
Input : test_list = [3, 7, 5, 3], repl_list = [7, 8]
Output : [3, 7, 8, 3]
Explanation : Replacement starts at 7 hence 7 and 8 are replaced.
Input : test_list = [3, 7, 5, 3, 9, 10], repl_list = [5, 6, 7, 4]
Output : [3, 7, 5, 6, 7, 4]
Explanation : Replacement starts at 5 and goes till end of list.
Method 1: Using list comprehension + list slicing The combination of above functionalities can be used to solve this problem. In this, we extract the index of beginning element, and then perform the appropriate slicing of list according to requirements.
Python3
test_list = [ 5 , 2 , 6 , 4 , 7 , 1 , 3 ]
print ("The original list : " + str (test_list))
repl_list = [ 6 , 10 , 18 ]
idx = test_list.index(repl_list[ 0 ])
res = test_list[ :idx] + repl_list + test_list[idx + len (repl_list):]
print ("Substituted List : " + str (res))
|
Output :
The original list : [5, 2, 6, 4, 7, 1, 3]
Substituted List : [5, 2, 6, 10, 18, 1, 3]
Time complexity: O(n), where n is the length of the original list.
Auxiliary space: O(n), as we create a new list to store the substituted list.
Method 2: Using for loop and conditional statements
This method uses a for loop to iterate over the elements in the original list, and conditional statements to decide whether to add the element to the final substituted list, or to replace it with the elements from the replacement list.
First, we find the index of the first element of the replacement list by iterating over the elements of the original list using a for loop and checking if each element is equal to the first element of the replacement list. Once we find the index, we break out of the loop.
Python3
test_list = [ 5 , 2 , 6 , 4 , 7 , 1 , 3 ]
repl_list = [ 6 , 10 , 18 ]
for i in range ( len (test_list)):
if test_list[i] = = repl_list[ 0 ]:
idx = i
break
res = []
for i in range ( len (test_list)):
if i < idx:
res.append(test_list[i])
elif i = = idx:
for j in range ( len (repl_list)):
res.append(repl_list[j])
elif i > idx + len (repl_list) - 1 :
res.append(test_list[i])
print ( "Substituted List: " , res)
|
Output
Substituted List: [5, 2, 6, 10, 18, 1, 3]
Time complexity: O(n), where n is the length of the original list.
Auxiliary space: O(n)
Method 3: Using extend method:
Algorithm:
1.Find the index of the first element in the replacement list in the original list.
2.Create a new list that consists of the elements before the index, the replacement list, and the elements after the index plus the length of the replacement list.
3.Print the resulting list.
Python3
test_list = [ 5 , 2 , 6 , 4 , 7 , 1 , 3 ]
repl_list = [ 6 , 10 , 18 ]
idx = test_list.index(repl_list[ 0 ])
res = test_list[:idx]
res.extend(repl_list)
res.extend(test_list[idx + len (repl_list):])
print ( "Substituted List:" , res)
|
Output
Substituted List: [5, 2, 6, 10, 18, 1, 3]
Time complexity:
Finding the index of the first element in the replacement list in the original list takes O(n) time, where n is the length of the original list.
Slicing the original list to create the new list takes O(n) time, where n is the length of the original list.
Extending the new list with the replacement list and the remaining elements of the original list also takes O(n) time.
Printing the resulting list takes O(n) time.
Therefore, the overall time complexity of this code is O(n).
Space complexity:
The space complexity of the code is O(n + k), where n is the length of the original list and k is the length of the replacement list.
This is because we create a new list to hold the resulting list, which takes O(n + k) space, and we also use some constant space for storing variables and temporary values.
Method 4: Using the index() and insert() method
- Initialize the original list and the replacement list.
- Find the index of the first element of the replacement list in the original list.
- Use a for loop to insert the elements of the replacement list one by one into the original list, starting at the index found in step 2.
- Use a for loop to remove the elements of the original list that come after the index found in step 2 and before the end of the replacement list.
- Print the substituted list.
Python3
test_list = [ 5 , 2 , 6 , 4 , 7 , 1 , 3 ]
print ( "The original list : " + str (test_list))
repl_list = [ 6 , 10 , 18 ]
idx = test_list.index(repl_list[ 0 ])
for i in range ( len (repl_list)):
test_list.insert(idx + i, repl_list[i])
for i in range ( len (repl_list)):
test_list.pop(idx + len (repl_list))
print ( "Substituted List : " + str (test_list))
|
Output
The original list : [5, 2, 6, 4, 7, 1, 3]
Substituted List : [5, 2, 6, 10, 18, 1, 3]
Time complexity: O(n^2) because of the two for loops.
Auxiliary space: O(n) because of the insertion and popping of elements from the original list.
Method 5: Using the slice() function and the list() constructor
Here’s another approach to replace a substring from the initial element using the slice() function and the list() constructor.
Steps:
- Initialize the original list and the list to replace with.
- Find the index of the first element of the list to replace with using the index() method.
- Create a new list by concatenating the slice of the original list from the start to the index of the first element to replace with, the list to replace with, and the slice of the original list from the index of the first element to replace with plus the length of the list to replace with to the end.
- Print the substituted list.
Python3
test_list = [ 5 , 2 , 6 , 4 , 7 , 1 , 3 ]
print ( "The original list : " + str (test_list))
repl_list = [ 6 , 10 , 18 ]
idx = test_list.index(repl_list[ 0 ])
res = list (test_list[:idx]) + repl_list + list (test_list[idx + len (repl_list):])
print ( "Substituted List : " + str (res))
|
Output
The original list : [5, 2, 6, 4, 7, 1, 3]
Substituted List : [5, 2, 6, 10, 18, 1, 3]
Time complexity: O(n), where n is the length of the original list.
Auxiliary space: O(n), where n is the length of the original list (to store the new list).
Similar Reads
Replace Multiple Lines From A File Using Python
In Python, replacing multiple lines in a file consists of updating specific contents within a text file. This can be done using various modules and their associated functions. In this article, we will explore three different approaches along with the practical implementation of each approach in term
3 min read
Remove Multiple Elements from List in Python
In this article, we will explore various methods to remove multiple elements from a list in Python. The simplest way to do this is by using a loop. A simple for loop can also be used to remove multiple elements from a list. [GFGTABS] Python a = [10, 20, 30, 40, 50, 60, 70] # Elements to remove remov
3 min read
Python | Remove particular element from tuple list
Since the advent of the popularity of Python in data analysis, we have a list of tuples as a container in many of our problems. Sometimes, while data preprocessing, we might have a problem in which we need to completely remove a particular element from a list of tuples. Let's discuss a way in which
7 min read
Python program to replace first 'K' elements by 'N'
Given a List, replace first K elements by N. Input : test_list = [3, 4, 6, 8, 4, 2, 6, 9], K = 4, N = 3 Output : [3, 3, 3, 3, 4, 2, 6, 9] Explanation : First 4 elements are replaced by 3. Input : test_list = [3, 4, 6, 8, 4, 2, 6, 9], K = 2, N = 10 Output : [10, 10, 6, 8, 4, 2, 6, 9] Explanation : Fi
4 min read
Python | Replace list elements with its ordinal number
Given a list of lists, write a Python program to replace the values in the inner lists with their ordinal values. Examples: Input : [[1, 2, 3], [ 4, 5, 6], [ 7, 8, 9, 10]]Output : [[0, 0, 0], [1, 1, 1], [2, 2, 2, 2]]Input : [['a'], [ 'd', 'e', 'b', 't'], [ 'x', 'l']]Output : [[0], [1, 1, 1, 1], [2,
5 min read
Python - Replace Elements greater than K
Given element list, replace all elements greater than K with given replace character. Input : test_list = [3, 4, 7, 5, 6, 7], K = 5, repl_chr = None Output : [3, 4, None, 5, None, None] Explanation : Characters are replaced by None, greater than 5. Input : test_list = [3, 4, 7, 5, 6, 7], K = 4, repl
4 min read
Python | Remove repeated sublists from given list
Given a list of lists, write a Python program to remove all the repeated sublists (also with different order) from given list. Examples: Input : [[1], [1, 2], [3, 4, 5], [2, 1]] Output : [[1], [1, 2], [3, 4, 5]] Input : [['a'], ['x', 'y', 'z'], ['m', 'n'], ['a'], ['m', 'n']] Output : [['a'], ['x', '
2 min read
Shrink List for Repeating Elements - Python
We are given a list of elements that may contain repeated values. Our task is to shrink the list by ensuring that each repeated element appears only once while maintaining the order of their first occurrence. For example, if the input list is [2, 3, 2, 5, 3, 5], the output should be [2, 3, 5]. Using
3 min read
Getting an Element from Tuple of Tuples in Python
Tuples in Python are versatile data structures that allow you to store and organize collections of elements. When dealing with tuples of tuples, accessing specific elements becomes essential for effective data manipulation. In this article, we'll explore some different methods to retrieve elements f
2 min read
Python - Replace Substrings from String List
The task of replacing substrings in a list of strings involves iterating through each string and substituting specific words with their corresponding replacements. For example, given a list a = ['GeeksforGeeks', 'And', 'Computer Science'] and replacements b = [['Geeks', 'Gks'], ['And', '&'], ['C
3 min read