Search code examples
pythonlistfor-looplist-comprehensionvectorization

Modify list elements whose indices are defined by a list without a for loop


I want to modify list elements (e.g. putting them equal to 1) whose indices are defined by a list. A (wrong) idea could be:

my_list = [1,2,3,11,22,4]
my_index = [1,3,4]

[my_list[i] = 1 for i in my_index]

There is always the brute forcing:

for i in my_index:
   my_list[i]  = 1

Is there a more efficient way to do this? Is there a way to vectorize this problem? I can also keep different element types from the list.


Solution

  • There's nothing wrong with the "brute forcing", it's readable and clear. There are ways to do this with e.g. numpy arrays that may be faster. But do you really need more speed?