Home > Software engineering >  Substitute values in a list at multiple indices
Substitute values in a list at multiple indices

Time:10-27

Suppose I have the list:

mylist = [0] * 46

I want to set mylist[i] = 1, for each index in the list

indices_list = [0, 30, 40, 41]

Right now, I'm using a simple and readable for loop, since in Python you cannot use a list of indices as indices in a list (i.e., mylist[indices_list] = 1 is not valid Python code):

for i in indices_list:
    mylist[i] = 1

and it works nicely. However, I've been told that it would be better to use a list comprehension. Is this true? If so, how would I do it, and what would be the advantage with respect to my simple for loop?

CodePudding user response:

Nah, it is not better. A list comprehension always creates a new list object. That means it has to process every element of the 46! A simple loop over the list of only 4 indices is just fine!

CodePudding user response:

What you have done is absolutely fine, but if you are looking for a list-comprehension solution, following will work (but less efficient than what you already have):

>>> [1 if i in indices_list else v for i,v in enumerate(mylist)]
[1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0]

CodePudding user response:

Lots of resources around this problem point in the direction that "at the end of the day, a loop is fine". I don't like solutions which try to import and leverage libraries (i.e. numpy, pandas), given that creating those objects comes with a cost. If you are already dealing with those objects, it is a natural thing to do obviously, but if you need to create one just to leverage a specific method and avoid a simple loop, maybe it is not always worth it.

  • Related