-1

What is the most efficient way to add an integer to part of a list?

Example :

input : [1,5,3,7,4,3]

range of list to modify is 2,4

add 3 to range

output : [1,5,6,10,7,3]

Explanation :

First get the sublist using indexes 2 and 4. Then add 3 to the values in that index. then return a list containing the modified range.

I tried using a loop but its not fast enough. Need a faster method.

AutoBootDisk
  • 89
  • 1
  • 14

2 Answers2

6

Adding a number to any number (supposedly sufficiently small as from the given eg.) is constant amount of time. You will have to iterate through those many list elements as in the provided range and add a number to them which is of the order of the length of the range. I don't think you can improve upon this task (i.e. which is asked in the question) although you can save some time on the overall program by handling the list as a generator object if you are dealing with very large amounts of data.

Ishan Srivastava
  • 1,129
  • 1
  • 11
  • 29
4

You can slice the list and then use iterator operations, which is faster than looping with an index:

l = [1,5,3,7,4,3]
l[2:5] = map((3).__add__, l[2:5])

l then becomes [1, 5, 6, 10, 7, 3].

blhsing
  • 91,368
  • 6
  • 71
  • 106