VOOZH about

URL: https://www.geeksforgeeks.org/python/python-specific-range-addition-in-list/

⇱ Python - Specific Range Addition in List - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Python - Specific Range Addition in List

Last Updated : 28 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.

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. 

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"

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.


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.

Comment