Python Specific Range Addition in List (original) (raw)
Last Updated : 25 Apr, 2025
Sometimes, while working with Python, we need to perform an edition in the Python list. And sometimes we need to perform this to a specific index range in it. This kind of application can have applications in many domains. Let us discuss certain ways in which this task can be performed.
Method #1: Using loop
This is a brute way in which this task can be performed. In this, we just iterate through the specified range in which the edition has to be performed.
Python3
test_list
=
[
4
,
5
,
6
,
8
,
10
,
11
]
print
(
"The original list is : "
+
str
(test_list))
i, j
=
2
,
5
for
idx
in
range
(i, j):
`` test_list[idx]
+
=
3
print
(
"List after range addition : "
+
str
(test_list))
Output :
The original list is : [4, 5, 6, 8, 10, 11] List after range addition : [4, 5, 9, 11, 13, 11]
Time Complexity: O(n) where n is the number of elements in the list “test_list”.
Auxiliary Space: O(1), constant extra space is needed
Method #2: Using list comprehension
This task can also be performed using list comprehension. This method uses the same way as above but it’s a shorthand for the above.
Python3
test_list
=
[
4
,
5
,
6
,
8
,
10
,
11
]
print
(
"The original list is : "
+
str
(test_list))
i, j
=
2
,
5
test_list[i: j]
=
[ele
+
3
for
ele
in
test_list[i: j]]
print
(
"List after range addition : "
+
str
(test_list))
Output :
The original list is : [4, 5, 6, 8, 10, 11] List after range addition : [4, 5, 9, 11, 13, 11]
Method #3: Using numpy Here is one approach using numpy library:
Note: Install numpy module using command “pip install numpy”
Python3
import
numpy as np
test_list
=
[
4
,
5
,
6
,
8
,
10
,
11
]
print
(
"The original list is : "
+
str
(test_list))
i, j
=
2
,
5
test_list
=
np.array(test_list)
test_list[i:j]
+
=
3
print
(
"List after range addition : "
+
str
(test_list.tolist()))
Output:
The original list is : [4, 5, 6, 8, 10, 11] List after range addition : [4, 5, 9, 11, 13, 11]
Time Complexity: O(n), where n is the length of the list.
Auxiliary Space: O(n), as a numpy array of the same length as the list is created.
Explanation:
- Import the numpy library
- Convert the list to a numpy array
- Add 3 to the specific range (i:j) of the numpy array
- Convert the numpy array back to a list and print the result.
Method 4: Using the slice notation and the built-in map function.
Python3
test_list
=
[
4
,
5
,
6
,
8
,
10
,
11
]
i, j
=
2
,
5
test_list[i:j]
=
map
(
lambda
x: x
+
3
, test_list[i:j])
print
(
"List after range addition : "
+
str
(test_list))
Output
List after range addition : [4, 5, 9, 11, 13, 11]
Time complexity of O(n), where n is the length of the list.
Auxiliary space: O(1), as we’re only modifying the original list and not creating any additional data structures.