Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Python – Substitute prefix part of List
When working with lists, you may need to substitute the prefix (beginning) part of one list with another list. Python provides a simple approach using list slicing with the : operator and the len() function.
What is Prefix Substitution?
Prefix substitution means replacing the first N elements of a list with elements from another list, where N is the length of the replacement list.
Example
Here's how to substitute the prefix part of a list ?
# Define two lists
original_list = [29, 77, 19, 44, 26, 18]
replacement_list = [15, 44, 82]
print("Original list:")
print(original_list)
print("Replacement list:")
print(replacement_list)
# Sort both lists for demonstration
original_list.sort()
replacement_list.sort()
print("Original list after sorting:")
print(original_list)
print("Replacement list after sorting:")
print(replacement_list)
# Substitute prefix: take replacement list + remaining elements from original
result = replacement_list + original_list[len(replacement_list):]
print("Result after prefix substitution:")
print(result)
Original list: [29, 77, 19, 44, 26, 18] Replacement list: [15, 44, 82] Original list after sorting: [18, 19, 26, 29, 44, 77] Replacement list after sorting: [15, 44, 82] Result after prefix substitution: [15, 44, 82, 29, 44, 77]
How It Works
The operation replacement_list + original_list[len(replacement_list):] works as follows:
len(replacement_list)returns 3 (length of replacement list)original_list[3:]extracts elements from index 3 onwards:[29, 44, 77]Concatenation combines:
[15, 44, 82] + [29, 44, 77] = [15, 44, 82, 29, 44, 77]
Alternative Approaches
You can also use list slicing assignment for in-place substitution ?
# In-place prefix substitution
original = [18, 19, 26, 29, 44, 77]
replacement = [15, 44, 82]
print("Before substitution:", original)
# Replace first 3 elements
original[:len(replacement)] = replacement
print("After substitution:", original)
Before substitution: [18, 19, 26, 29, 44, 77] After substitution: [15, 44, 82, 29, 44, 77]
Conclusion
Use list concatenation with slicing to substitute the prefix part of a list. The key is using len(replacement_list) to determine where to start extracting from the original list.
