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
# Python3 code to demonstrate working of
# Replace substring from Initial element
# Using list slicing + list comprehension
# initializing list
test_list = [5, 2, 6, 4, 7, 1, 3]
# printing original list
print("The original list : " + str(test_list))
# initializing repl_list
repl_list = [6, 10, 18]
# Replace substring from Initial element
# Extracting index
idx = test_list.index(repl_list[0])
# Slicing till index, and then adding rest of list
res = test_list[ :idx] + repl_list + test_list[idx + len(repl_list):]
# printing result
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]
# find the index of the first element of the replacement list
for i in range(len(test_list)):
if test_list[i] == repl_list[0]:
idx = i
break
# replace the substring from the initial element
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)
OutputSubstituted 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]
# Find the index of the first element in repl_list in test_list
idx = test_list.index(repl_list[0])
# 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.
res = test_list[:idx]
res.extend(repl_list)
res.extend(test_list[idx+len(repl_list):])
# Print the resulting list
print("Substituted List:", res)
#This code is contributed by Jyothi pinjala.
OutputSubstituted 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
# Python3 code to demonstrate working of
# Replace substring from Initial element
# Using the index() and insert() method
# initializing list
test_list = [5, 2, 6, 4, 7, 1, 3]
# printing original list
print("The original list : " + str(test_list))
# initializing repl_list
repl_list = [6, 10, 18]
# Replace substring from Initial element
# Finding the index of the first element of the replacement list
idx = test_list.index(repl_list[0])
# Inserting the elements of the replacement list one by one into the original list
for i in range(len(repl_list)):
test_list.insert(idx+i, repl_list[i])
# Removing the elements of the original list that come after the index found in step 2 and before the end of the replacement list
for i in range(len(repl_list)):
test_list.pop(idx+len(repl_list))
# printing result
print("Substituted List : " + str(test_list))
OutputThe 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
# Python3 code to demonstrate working of
# Replace substring from Initial element
# Using the slice() function and the list() constructor
# initializing list
test_list = [5, 2, 6, 4, 7, 1, 3]
# printing original list
print("The original list : " + str(test_list))
# initializing repl_list
repl_list = [6, 10, 18]
# Replace substring from Initial element
# Extracting index
idx = test_list.index(repl_list[0])
# Slicing and Concatenating
res = list(test_list[:idx]) + repl_list + list(test_list[idx + len(repl_list):])
# printing result
print("Substituted List : " + str(res))
OutputThe 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
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, 2
5 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
5 min read
Replace Substrings from String List - Python 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
Python | Remove given element from list of lists The deletion of elementary elements from list has been dealt with many times, but sometimes rather than having just a one list, we have list of list where we need to perform this particular task. Having shorthands to perform this particular task can help. Let's discuss certain ways to perform this p
6 min read
Python | Remove trailing empty elements from given list When working with lists in Python, it's common to encounter lists with extra None elements at the end. These trailing None values can cause issues in our programs . We can remove these trailing None elements using simple methods like slicing, loops, or filter.Using List Slicing Slicing is a very eff
3 min read
Python | Get first element of each sublist Given a list of lists, write a Python program to extract first element of each sublist in the given list of lists. Examples: Input : [[1, 2], [3, 4, 5], [6, 7, 8, 9]] Output : [1, 3, 6] Input : [['x', 'y', 'z'], ['m'], ['a', 'b'], ['u', 'v']] Output : ['x', 'm', 'a', 'u'] Â Approach #1 : List compre
3 min read
Replace index elements with elements in Other List-Python The task of replacing index elements with elements from another list involves mapping the indices from one list to the corresponding elements in a second list. For each index in the first list, the element at that index is retrieved from the second list and stored in a new result list. For example,
4 min read
Python | Remove Initial K column elements Sometimes, while working with Matrix data, we can have stray elements that attached at front end of each row of matrix. This can be undesired at times and wished to be removed. Letâs discuss certain ways in which this task can be performed. Method #1 : Using loop + del + list slicing The combination
4 min read
Update Each Element in Tuple List - Python The task of updating each element in a tuple list in Python involves adding a specific value to every element within each tuple in a list of tuples. This is commonly needed when adjusting numerical data stored in a structured format like tuples inside lists. For example, given a = [(1, 3, 4), (2, 4,
3 min read
Python | Replace tuple according to Nth tuple element Sometimes, while working with data, we might have a problem in which we need to replace the entry in which a particular entry of data is matching. This can be a matching phone no, id etc. This has it's application in web development domain. Let's discuss certain ways in which this task can be perfor
8 min read