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 Tutorial | Learn Python Programming Language Python Tutorial â Python is one of the most popular programming languages. Itâs simple to use, packed with features and supported by a wide range of libraries and frameworks. Its clean syntax makes it beginner-friendly.Python is:A high-level language, used in web development, data science, automatio
10 min read
Python Interview Questions and Answers Python is the most used language in top companies such as Intel, IBM, NASA, Pixar, Netflix, Facebook, JP Morgan Chase, Spotify and many more because of its simplicity and powerful libraries. To crack their Online Assessment and Interview Rounds as a Python developer, we need to master important Pyth
15+ min read
Python OOPs Concepts Object Oriented Programming is a fundamental concept in Python, empowering developers to build modular, maintainable, and scalable applications. By understanding the core OOP principles (classes, objects, inheritance, encapsulation, polymorphism, and abstraction), programmers can leverage the full p
11 min read
Python Projects - Beginner to Advanced Python is one of the most popular programming languages due to its simplicity, versatility, and supportive community. Whether youâre a beginner eager to learn the basics or an experienced programmer looking to challenge your skills, there are countless Python projects to help you grow.Hereâs a list
10 min read
Python Exercise with Practice Questions and Solutions Python Exercise for Beginner: Practice makes perfect in everything, and this is especially true when learning Python. If you're a beginner, regularly practicing Python exercises will build your confidence and sharpen your skills. To help you improve, try these Python exercises with solutions to test
9 min read
Python Programs Practice with Python program examples is always a good choice to scale up your logical understanding and programming skills and this article will provide you with the best sets of Python code examples.The below Python section contains a wide collection of Python programming examples. These Python co
11 min read
Enumerate() in Python enumerate() function adds a counter to each item in a list or other iterable. It turns the iterable into something we can loop through, where each item comes with its number (starting from 0 by default). We can also turn it into a list of (number, item) pairs using list().Let's look at a simple exam
3 min read
Python Data Types Python Data types are the classification or categorization of data items. It represents the kind of value that tells what operations can be performed on a particular data. Since everything is an object in Python programming, Python data types are classes and variables are instances (objects) of thes
9 min read
Python Introduction Python was created by Guido van Rossum in 1991 and further developed by the Python Software Foundation. It was designed with focus on code readability and its syntax allows us to express concepts in fewer lines of code.Key Features of PythonPythonâs simple and readable syntax makes it beginner-frien
3 min read
Input and Output in Python Understanding input and output operations is fundamental to Python programming. With the print() function, we can display output in various formats, while the input() function enables interaction with users by gathering input during program execution. Taking input in PythonPython input() function is
8 min read