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 Program to replace list elements within a range with a given number
When working with Python lists, you may need to replace multiple elements within a specific range with the same value. This can be efficiently accomplished using list slicing combined with list multiplication.
Syntax
The basic syntax for replacing elements within a range is ?
list[start:end] = [new_value] * (end - start)
Where:
-
start− starting index (inclusive) -
end− ending index (exclusive) -
new_value− the value to replace with
Basic Example
Here's how to replace elements at indices 4 to 7 with the number 9 ?
numbers = [42, 42, 18, 73, 11, 28, 29, 0, 10, 16, 22, 53, 41]
print("Original list:")
print(numbers)
start_index, end_index = 4, 8
replacement_value = 9
numbers[start_index:end_index] = [replacement_value] * (end_index - start_index)
print("After replacement:")
print(numbers)
Original list: [42, 42, 18, 73, 11, 28, 29, 0, 10, 16, 22, 53, 41] After replacement: [42, 42, 18, 73, 9, 9, 9, 9, 10, 16, 22, 53, 41]
How It Works
The expression [replacement_value] * (end_index - start_index) creates a new list with the replacement value repeated the exact number of times needed. List slicing then assigns this new list to the specified range, effectively replacing the original elements.
Replace from Beginning
You can replace elements from the start of the list ?
data = [1, 2, 3, 4, 5, 6, 7, 8]
print("Original list:", data)
# Replace first 3 elements with 0
data[:3] = [0] * 3
print("After replacement:", data)
Original list: [1, 2, 3, 4, 5, 6, 7, 8] After replacement: [0, 0, 0, 4, 5, 6, 7, 8]
Replace Until End
You can replace elements from a specific index to the end of the list ?
items = ['a', 'b', 'c', 'd', 'e', 'f']
print("Original list:", items)
# Replace from index 3 to end with 'x'
start = 3
items[start:] = ['x'] * (len(items) - start)
print("After replacement:", items)
Original list: ['a', 'b', 'c', 'd', 'e', 'f'] After replacement: ['a', 'b', 'c', 'x', 'x', 'x']
Key Points
- List slicing with assignment modifies the original list in-place
- The range is defined as
[start:end]where start is inclusive and end is exclusive - List multiplication
[value] * ncreates a list with the value repeated n times - This method preserves the list length when replacing the same number of elements
Conclusion
Using list slicing with list multiplication provides an efficient way to replace multiple consecutive elements in a Python list. This technique is memory-efficient and maintains the original list structure while allowing flexible range-based replacements.
