![]() |
VOOZH | about |
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.
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.
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"
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:
Method 4: Using the slice notation and the built-in map function.
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.