1

Imagine that you have a list like this one:

[0, 0, 0, 0, 0, 0]

And you want to add a number, lets say 5 but just between the positions 1 and 4, so the resulting array would be:

[0, 5, 5, 5, 5, 0]

Is there a way to use map to do this? Right now I'm using a for loop and range but find it a bit inefficient.

Thanks!

loot
  • 23
  • 4
  • A `map` in no way is more efficient that a `for` loop I believe as it also internally needs to iterate over the elements to modify them. – Krishna Chaurasia Apr 01 '21 at 11:40
  • `l[1:5] = [5 for _ in range(4)]` – Sayse Apr 01 '21 at 11:44
  • 2
    Since you're looking for performance, did you compare your for loop time to answers? Using timeit, I find a for loop is faster than all of them i.e. `for i in range(1, 5): arr[i] = 5` where arr is the original list. – DarrylG Apr 01 '21 at 12:09

3 Answers3

2
spam = [0, 0, 0, 0, 0, 0]
spam[1:5] = map(lambda x: x+5, spam[1:5])
print(spam)
buran
  • 13,682
  • 10
  • 36
  • 61
  • 2
    This is *slower* than simply iterating over the desired indices, as it has to make a (shallow) copy of the list before it can perform the in-place assignments. – chepner Apr 01 '21 at 14:29
1

If you are open to using external libraries, you can use numpy for this task:

> import numpy as np
> numbers = [0, 0, 0, 0, 0, 0]
> numbers_array = np.asarray(numbers)
> numbers_array[1:4] += 5
> print(numbers_array)
array([0, 5, 5, 5, 5, 0])

And if you need it, convert it back to list:

> numbers = numbers_array.tolist()

If your application for the list involves this kind of operations frequently, I suggest you take a look to the numpy library to see if arrays are a better fit for your task

1

To answer your question, you can use something along the lines of:

sample_array = [0 ,0, 0, 0, 0]

def perform_operation_on_slice(array, lower_bound, upper_bound, operation):
    '''
    array       : the array on which the operation is to be perfomed
    lower_bound : the starting index
    upper_bound : the ending index
    operation   : a function that is to be performed on array[ lower_bound : upper_bound ]
    '''

    array[lower_bound:upper_bound] = map(operation, array[ lower_bound : upper_bound ])

# sample case:
arr = [0,0,0,0,0,0]

perform_operation_on_slice(arr, 1, 4, lambda x: x+5)

print(arr)

# [0, 5, 5, 5, 0, 0]

Hope this answer helps :)

Novus Edge
  • 131
  • 1
  • 5